【问题标题】:Can't get association working in form无法让协会以形式工作
【发布时间】:2012-03-08 22:08:20
【问题描述】:

我很难与simple_form 建立关联。

我有以下型号。

class Product < ActiveRecord::Base
  belongs_to :Retailer
end

class Retailer < ActiveRecord::Base
   has_many :Products
end

我的部分表单 (products/_form.html.erb) 包含以下内容

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

它可以在没有关联的情况下工作,但使用它会出现以下错误:

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

我(显然)对此很陌生,但无法解决这个问题。

编辑:检查过我会运行迁移并且它们是最新的。 Retailer 表有一个 id 列!

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

化学文件:

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

【问题讨论】:

    标签: ruby-on-rails rails-activerecord


    【解决方案1】:

    由于您的产品模型和表单中分别有belongs_to :Retailer&lt;% f.association :retailer %&gt;,因此您需要在产品表中添加一个retailer_id 列。

    您的迁移文件中缺少 t.references :retailer,用于创建产品表。 这就是为什么,我引用你的话“它可以在没有关联的情况下工作,但错误是undefined method 'retailer_id' for #&lt;Product:0x007ffbe0f7d530&gt;

    是的,retailers 表有一个 id 列,但为了从产品中引用零售商,您的 products 表需要一个 retailer_id 列。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-14
      • 2019-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多