如何解决RoR如何在不丢失信息的情况下在同一块中执行多个构建关联?
| 我现在刚刚开始一个小项目,所以我可以了解RoR 3中的更多新功能。因此,我正在阅读有关对象之间的关联的信息,更具体地讲是“ build”方法。亩的问题是当我使用它一次没有问题像:@note = product.notes.build(:product => product)
然后我更改了note的某些属性,没问题。
问题是请注意belongs_to
两个对象Product
和User
,所以当我创建对象时,我需要建立该关联,所以我需要做类似的事情
@note = product.notes.build(:product => product)
@note = user.notes.build(:user => user)
在第二次构建之后,我已经失去了与Product的关联,因为\“ build \”方法将返回一个新实例。
我是否缺少建立协会的方式?我应该换一种方式吗?
谢谢 !
# 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][:rating]
@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
这是产品的定义
class Product < ActiveRecord::Base
validates :name,:presence => true
has_many :notes,:dependent => :destroy
end
和注意
class Note < ActiveRecord::Base
belongs_to :product
belongs_to :user
end
解决方法
选择您喜欢的方式:
@note = Note.new(:user => user,:product => product)
@note = product.notes.build(:user => user)
@note = user.notes.build(:product => product)
如果您写了两个@note =
,则将另一个对象重新分配给@note
,第一个对象丢失了。
您也可以这样写:
@note = product.notes.build
@note.user = user
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。