开发者

RoR How to do more than one Build association in the same block without loosing information?

I'm just starting now a small project so I can learn more of the new possibilities in RoR 3 . So I was reading about associations between objects, more specific the "build" method. Mu problem is when I use it one time no problem like:

@note = product.notes.build(:product => product)

and then I change some attributes of note and no problem.

The problem is note belongs_to two objects Product and User so when I'm creating an object I need to build that association so I need to do something like

@note = product.notes.build(:product => product)
@note = user.notes.build(:user => user)

After the second build I've lost the association with Product because the "build" method will return a new instance.

Am I missing something of the way I should build the associations ? Should I do it another way ?

Thanks !

# POST /notes
# POST /notes.xml
def create
  user = current_user
  product = Product.find(2)
  @note = product.notes.build(:product => product)
  @note = user.notes.build(:user => user)

  @note.rating = params[:note][:rati开发者_运维百科ng]
  @note.text = params[:note][:text]
  respond_to do |format|
    if @note.save
      format.html { redirect_to(@note, :notice => 'Note was successfully created.') }
      format.xml  { render :xml => @note, :status => :created, :location => @note }
    else
      format.html { render :action => "new" }
      format.xml  { render :xml => @note.errors, :status => :unprocessable_entity }
    end
  end
end

Here goes the definition of Product

class Product < ActiveRecord::Base
  validates :name,  :presence => true
  has_many :notes ,:dependent => :destroy
end

and Note

class Note < ActiveRecord::Base
  belongs_to :product
  belongs_to :user
end


Pick the way you prefer:

  • @note = Note.new(:user => user, :product => product)
  • @note = product.notes.build(:user => user)
  • @note = user.notes.build(:product => product)

If you write two @note =, you reassign another object to @note and the first one is lost.

You can also write something like this:

@note = product.notes.build
@note.user = user
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜