1

我有下面的方法将数据保存到 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
4

2 回答 2

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
于 2012-11-21T01:34:26.320 回答
0

您需要在保存 @newUser 之前建立 UserDetails 关联

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

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

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

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

于 2012-11-21T00:43:48.337 回答