Rails如何获取关联的模型属性

时间:2012-11-21 00:33:01

标签: ruby-on-rails ruby ruby-on-rails-3

我有下面的方法,它将数据保存到users表以及user_details表。

当我将@newUser变量传递给EmailMailer时,我无法访问user_details属性。如何在不必重新查询数据库的情况下传递@newUser对象中的user_details?

模型

class User < ActiveRecord::Base
  has_one :user_details, :dependent => :destroy
  accepts_nested_attributes_for :user_details
  attr_accessible :email, :password, :password_confirmation, :remember_me, :username, :login, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company, :user_details_attributes
end

class UserDetails < ActiveRecord::Base
  belongs_to :user
  attr_accessible :first_name, :last_name, :home_phone, :cell_phone, :work_phone, :birthday, :home_address, :work_address, :position, :company
end

控制器

# POST /users
def create
        @newUser = User.new(params[:user], :include =>:user_details)

        # create password
        require 'securerandom'
    password = SecureRandom.urlsafe_base64(8)

        @newUser.password = password

        respond_to do |format|
            if @newUser.save

                @newUser.build_user_details
                # Tell the UserMailer to send a welcome Email after save
                EmailMailer.welcome_email(@newUser).deliver
                # To be used in dev only. Just tests if the email was queued for sending.
                #assert ActionMailer::Base.deliveries.empty?
                format.html {
                    flash[:success] = "User created successfully"
                    redirect_to(contacts_path)
                }
            else 
                format.html {
                    flash[:error] = flash[:error].to_a.concat resource.errors.full_messages
                    redirect_to(contacts_path)
                }
            end
        end
  end

2 个答案:

答案 0 :(得分:1)

这样的事情可能就是你所追求的。

class User < ActiveRecord::Base
  has_one :user_details
  accepts_nested_attributes_for :user_details
  after_initialize :build_user_details
  ...
end

# In controller
def create
  @new_user = User.new
  @new_user.attributes = params[:user]
  if @new_user.save
    # do mail thing
  else
    # other thing
  end
end

答案 1 :(得分:0)

您需要在保存@newUser

之前构建UserDetails关联
@newUser.build_user_details
if @newUser.save
  #send mailer
else
  #do something else
end

或者,您可以在保存@newuser后使用创建操作

if @newUser.save
   @newUser.create_user_details
   #send mailer
else
   #do something else
end

顺便说一句,Ruby / Rails约定是将snake_case用于变量。所以@newUser应该是@new_user。