簡體   English   中英

Rails如何獲取關聯的模型屬性

[英]Rails how to get associated model attributes

我有下面的方法將數據保存到用戶表以及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

像這樣的事情可能會做你所追求的。

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

您需要先建立UserDetails關聯,然后再保存@newUser

@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

順便說一下,R​​uby / Rails約定是對變量使用snake_case。 所以@newUser應該是@new_user。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM