I’m having difficulties getting an association to work with simple_form.
I have the following models.
class Product < ActiveRecord::Base
belongs_to :Retailer
end
and
class Retailer < ActiveRecord::Base
has_many :Products
end
My form partial (products/_form.html.erb) contains the following
<%= simple_form_for(@product) do |f| %>
...
<% f.input :currency %>
<% f.association :retailer %>
...
It works without the association, but with it I get the following error:
undefined method `retailer_id' for #<Product:0x007ffbe0f7d530>
I’m (obviously) quite new to this, but haven’t been able to work this out.
edit: checked I’d run migrations and they are up-to-date. The Retailer table has an id column!
> Retailer.all
Retailer Load (0.2ms) SELECT "retailers".* FROM "retailers"
=> [#<Retailer id: 1, name: "Retailer 1" etc...
chema file:
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
Since you have
belongs_to :Retailerand<% f.association :retailer %>in your model and form for Product respectively, you’ll need to add aretailer_idcolumn to your products table.You are missing
t.references :retailerin your migration file for creating products table.That is why, I quote you “it works without the association, but with it the error is
undefined method 'retailer_id' for #<Product:0x007ffbe0f7d530>“Yes, the retailers table has an
idcolumn but in order to reference a retailer from a product, your products table requires aretailer_idcolumn.