2012-03-08 87 views
1

我無法與simple_form建立關聯。無法在表單中獲得關聯工作

我有以下型號。

class Product < ActiveRecord::Base 
    belongs_to :Retailer 
end 

class Retailer < ActiveRecord::Base 
    has_many :Products 
end 

我的表單部分(產品/ _form.html.erb)包含以下

<%= simple_form_for(@product) do |f| %> 
... 
<% f.input :currency %> 
<% f.association :retailer %> 
... 

這工作沒有關聯,但與它,我得到以下錯誤:

undefined method `retailer_id' for #<Product:0x007ffbe0f7d530> 

我是(顯然)對此很新,但還沒有能夠解決這個問題。

編輯:checked我會運行遷移,他們是最新的。零售商表有一個ID列!

> Retailer.all 
Retailer Load (0.2ms) SELECT "retailers".* FROM "retailers" 
=> [#<Retailer id: 1, name: "Retailer 1" etc... 

CHEMA文件:

ActiveRecord::Schema.define(:version => 20120308195055) do 

    create_table "alerts", :force => true do |t| 
    t.string "url",  :null => false 
    t.datetime "created_at", :null => false 
    t.datetime "updated_at", :null => false 
    end 

    create_table "products", :force => true do |t| 
     t.string "title",      :null => false 
     t.integer "price_cents", :default => 0, :null => false 
     t.string "currency",     :null => false 
     t.string "asin",      :null => false 
     t.datetime "created_at",     :null => false 
     t.datetime "updated_at",     :null => false 
    end 

    create_table "retailers", :force => true do |t| 
     t.string "name",  :null => false 
     t.datetime "created_at", :null => false 
     t.datetime "updated_at", :null => false 
    end 

    end 

回答

0

既然你已經在你的模型belongs_to :Retailer<% f.association :retailer %>分別形成了產品,你需要一個retailer_id列添加到您的產品表。

您在用於創建產品表的遷移文件中缺少t.references :retailer。 這就是爲什麼,我給你報「它工作沒有關聯,但與它的錯誤是undefined method 'retailer_id' for #<Product:0x007ffbe0f7d530>

是,零售商表有一個id列,但爲了從一個產品參考零售商,您的產品表需要retailer_id列。