2013-05-20 56 views
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 

回答

1

可以旋轉它:

def inbound 
    @gift = Gift.new(params.slice(*Gift.new.acceptable))  
    if Gwgiftwhip.create({user_id: @gift.user_id, 
          gift: @gift}, without_protection: true) 
    ... 
    end 
end 

您可能還conisder上Gwgiftwhip首要gift=,使得在設定giftuser_id自動。例如:

class Gwgiftwhip 
    has_one :gift, :autosave => true, :dependent => :destroy 

    def gift=(gift) 
    super(gift) 
    self.user_id = gift.user_id 
    end 
end 
+0

謝謝。它看起來像.create()將返回新的對象,無論驗證傳遞,所以實際上添加(不)new_record? Gwgiftwhip.create({:user_id => @ gift.user_id,:gift => @gift},::without_protection => true).new_record?' –

+0

此外,有關重寫相關模型的setter方法。它工作得很好。對於其他用例,user_id需要是current_user,因此我可能會在其他地方使用您的建議。 –

相關問題