2012-03-08 86 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列。