0
我无法让create_association(attributes = {})方法在Rails中为相关模型工作。如何在ruby-on-rails中使用create_association
class Gwgiftwhip < ActiveRecord::Base
has_one :gift, :autosave => true, :dependent => :destroy
validates :gift, :presence => true
end
class Gift < ActiveRecord::Base
belongs_to :gwgiftwhip
end
的belongs_to section in the Active Record Associations Guide建议你应该能够使用的方法:create_association(属性= {})创建相关模型,并使用belongs_to的关联时保存。但是,由于相关模型参数'gift'未设置,下面的实现会导致保存错误。
class GiftsController < ApplicationController
...
def inbound
@gift = Gift.new(params.slice(*Gift.new.acceptable))
if @gift.create_gwgiftwhip({:user_id => @gift.user_id}, :without_protection => true)
...
end
end
下面的工作,但似乎是超出预期的用途。它正在创建一个相关模型,然后将其设置为相关模型。这需要另一步然后保存。
class GiftsController < ApplicationController
...
def inbound
@gift = Gift.new(params.slice(*Gift.new.acceptable))
@gift.create_gwgiftwhip({:user_id => @gift.user_id}, :without_protection => true).gift = @gift
if @gift.gwgiftwhip.save
...
end
end
谢谢。它看起来像.create()将返回新的对象,无论验证传递,所以实际上添加(不)new_record? Gwgiftwhip.create({:user_id => @ gift.user_id,:gift => @gift},::without_protection => true).new_record?' –
此外,有关重写相关模型的setter方法。它工作得很好。对于其他用例,user_id需要是current_user,因此我可能会在其他地方使用您的建议。 –