I've seen the undefined local variable in many threads, also I have seen adding relationships a lot, so please read the problem before suggesting it's answered elsewhere. (of course, if you do find an answer elsewhere, I will be just as grateful)
The tables are Services and Checks (in the context of a garage, the service is the type and the checks are what need to be carried out for any particular service). This is many to many, so I've got a has many through relationship set up.
The problem is, although everything is working fine, I am still getting the error:
undefined local variable or method `check_ids'
Line:
@service.service_checks.build(check_id: check_ids, service_id: @service.id )
Any attempt I make to define the variable seems to stop the relationships from working. Which leaves me clueless as to how to get everything working in harmony.
Models:
class Service < ActiveRecord::Base
has_many :service_checks, :dependent => :destroy
has_many :checks, :through => :service_checks
#attr_accessor :check_ids
accepts_nested_attributes_for :checks
accepts_nested_attributes_for :service_checks
end
class Check < ActiveRecord::Base
has_many :service_checks
has_many :services, :through => :service_checks
belongs_to :check_cat
end
class ServiceCheck < ActiveRecord::Base
belongs_to :service, dependent: :destroy
belongs_to :check, dependent: :destroy
accepts_nested_attributes_for :check, :reject_if => :all_blank
self.primary_key = [:service_id, :check_id]
end
My update function in Service looks like this:
def update
respond_to do |format|
if @service.update(service_params)
# This builds the relationships
@service.service_checks.build(check_id: check_ids, service_id: @service.id )
format.html { redirect_to @service, notice: 'Service was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @service.errors, status: :unprocessable_entity }
end
end
end
# Never trust parameters from the scary internet, only allow the white list through.
def service_params
params.require(:service).permit(:name, :price, :check_ids => [])
end
And my form is simply:
<%= f.association :checks,
as: :check_boxes,
label_method: :name,
value_method: :id,
label: 'Checks' %>