Hi
It seems if the nested part of the form includes a “select” then 2 bad
things happen:
-
On Edit, the select list does not set “option selected” so it shows
the first entry in the list which of course is often not correct. -
You can’t save the nested part!! as it stands.
When I save a new record I get the following error:
Country(#88962190) expected, got String(#76076140)
with the Params as follows:
{“utf8”=>“✓”,
“authenticity_token”=>“WMi/N+9RLnGvk8Y3fKUlwkWYJfXGOXzXSikH3a4uep4=”,
“product”=>{“name”=>“cccc”,
“prices_attributes”=>{“0”=>{“price”=>“1”,
“currency”=>“AUD”,
“country”=>“1”}}},
“commit”=>“Save”}
It seems the problem is “country”=>“1”. It seems to be really
looking for a Country model as in Country.find(1).
If I amend Params in the create method, prior to save, as follows, it
works perfectly!!!
params[:product][“prices_attributes”][“0”][“country”]=Country.find(1)
I am assuming I have done something wrong in my setup, models etc, but
after considerable research, I have absolutely no idea what it is.
I also assume if it is something I haven’t done correctly, then the
first problem above might also go away.
I would appreciate very much being enlightened.
Thank you.
My models - very simple
class Product < ActiveRecord::Base
has_many :prices
has_many :countries, :through => :prices
accepts_nested_attributes_for :prices,
:reject_if => lambda { |a|
a[:price].blank?},
:allow_destroy => true
scope :active, :conditions => ‘expired_on is null’
end
class Price < ActiveRecord::Base ### effectively a join table ut with
id
belongs_to :product
belongs_to :country
end
class Country < ActiveRecord::Base
has_many :prices
has_many :products, :through => :prices
end
The form:
= form_for @product do |f|
.field
= f.label :name
= f.text_field :name
= f.fields_for :prices do |p|
%p
= p.label :price, “Price”
= p.text_field :price, :size=>10
= p.label :price, “Currency”
= p.text_field :currency, :size=>6
= p.label :country, “Country”
= p.collection_select(:country, @countries, :id, :description)
.actions
= f.submit ‘Save’
The controller (excerpt):
def new
@product = Product.new
@product.prices.build
@countries = Country.all
respond_with(@product)
end
GET /products/1/edit
def edit
@product = Product.find(params[:id])
@countries = Country.all
end
POST /products
POST /products.xml
def create
@product = Product.new(params[:product])
@product.save
respond_with(@product)
end