So I have a categories model
class Category < ActiveRecord::Base
has_many :provider_categories
has_many :providers, :through => :provider_categories
end
and a provider model
class Provider < ActiveRecord::Base
has_many :provider_categories
has_many :categories, :through => :provider_categories
accepts_nested_attributes_for :provider_categories, :allow_destroy => true
end
here is my provider_category model
class ProviderCategory < ActiveRecord::Base
belongs_to :provider
belongs_to :category
end
I'm trying to create a nested form to include the categories into the provider form
= form_for @provider do |f|
...
-@categories.each.with_index do |category,index|
=f.fields_for :provider_category, category do |pl|
=pl.check_box :category_id
=pl.label category.name
=pl.hidden_field :provider_id, value: @provider.id
The checkbox is not cooperating when I load the page I get
undefined method `category_id' for #<Category:0x0000010184ff60>
EDIT:
if I change the :category_id to id it works but the html outpuy looks like this
<input name="provider[provider_category][id]" type="hidden" value="0"><input checked="checked" id="provider_provider_category_id" name="provider[provider_category][id]" type="checkbox" value="1">
<label for="provider_provider_category_Acupuncture">Acupuncture</label>
<input id="provider_provider_category_provider_id" name="provider[provider_category][provider_id]" type="hidden" value="1">
EDIT 2:
I ended up using check_box_tag
-@categories.each.with_index do |category|
=f.fields_for :provider_category, category do |pl|
.li
=check_box_tag "provider[provider_category][category_id]", category.id
=pl.label category.name
=pl.hidden_field :provider_id, value: @provider.id
Now the html output seems to be correct but it's not saving it. When I select multiple items this is the hash from saving
"provider"=>{"name"=>"Mr. Awesome", "phone"=>"999-999-9999", "email"=>"awesome@awesome.com", "address"=>"awesome land", "provider_category"=>{"category_id"=>"3", "provider_id"=>"1"}}, "commit"=>"Save", "id"=>"1"}
I did select 3 options but only the last one was added to the hash
I also added the provider categories in the strong params of provider controller
params.require(:provider).permit(..., :provider_categories => [:category_id, :provider_id])
Thanks for the help in advance