AS per your model definitions, ProviderCategory
has attributes category_id
and provider_id
. You are getting error as:
undefined method `category_id' for #<Category:0x0000010184ff60>
because instead of passing instance of ProviderCategory
, you have passed an instance of Category
class. Notice category
being passed in
=f.fields_for :provider_category, category do |pl|
and as there is no attribute named category_id
in model Category
you receive the error.
To resolve that, just update the fields_for
method call in your view as below:
=f.fields_for :provider_categories, category.provider_categories.build do |pl|
UPDATE
Also, you would have to update the strong params of ProvidersController
so that records for provider_categories
are saved correctly in database:
params.require(:provider).permit(..., :provider_categories_attributes => [:category_id, :provider_id])
Use provider_categories_attributes
and not provider_categories
UPDATE 2
OP had another problem, for the unchecked category_id
, value 0
was being passed and incorrect records with category_id
set as 0
were getting created in provider_categories
.
Suggested to reject those records by passing reject_if
option to accepts_nested_attributes_for
method call in Provider
model as below:
class Provider < ActiveRecord::Base
has_many :provider_categories
has_many :categories, :through => :provider_categories
accepts_nested_attributes_for :provider_categories, :allow_destroy => true, reject_if: proc { |attributes| attributes['category_id'] == "0" }
end
Checkbox was not passing the id's of checked categories, suggested to update the checkbox code as below:
=pl.check_box :category_id, {}, category.id, 0