2014-09-04 86 views
0

我的模型:多態關聯不保存價值

class LineItem < ActiveRecord::Base 
    attr_accessible :itemable 
    belongs_to :itemable, polymorphic: true 

    belongs_to :lead 
    belongs_to :cart 


end 

class House < ActiveRecord::Base 
    has_many :line_items, :as => :itemable 
end 

class Appartment < ActiveRecord::Base 
    has_many :line_items, :as => :itemable 
end 

line_item_controller:

def create 
     @line_item = @cart.line_items.build item: @object 
     respond_to do |format| 
     if @line_item.save 
      format.html { redirect_to @line_item.cart, 
      notice: 'Vakantiehuis toegevoegd in lijst.' } 
      format.json { render action: 'show', 
      status: :created, location: @line_item } 
     else 
      format.html { render action: 'new' } 
      format.json { render json: @line_item.errors, 
      status: :unprocessable_entity } 
     end 
     end 
    end 

private 
    def create_object 
     id = params[:house_id] || params[:appartment_id] 

     model = "House" if params[:house_id] 
     model = "Apartment" if params[:apartment_id] 
     model = model.constantize 

     @object = model.find(id) 
    end 

當一個新的項目列表中創建在DE TABLE line_items值(itemable_id,itemable_type)不會被保存。我在這裏做錯了什麼? thanks..remco

+0

使用Rails 3或4? – 2014-09-04 08:10:23

+0

而不是'model =「House」'和'model.constantize'你可以直接寫'model = House' – IS04 2014-09-04 08:16:55

回答

1

嘗試更換:

@cart.line_items.build item: @object 

到:

@cart.line_items.build itemable: @object 
+0

謝謝你的工作!將項目更改爲可迭代。 – Remco 2014-09-04 08:22:23

+0

我將房子或公寓添加到列表後...訪問者重定向到購物車...在展示模板中,我有一個循環與所有項目@ cart.line_items.each do | item |但是我怎樣才能將環路連接到相關的房子或公寓? – Remco 2014-09-04 08:24:13

+0

你可以寫:'link_to item.itemable' – IS04 2014-09-04 08:30:12