Note that there are some explanatory texts on larger screens.

plurals
  1. POAdding relationships with Has_Many Through. undefined local variable but everything works
    text
    copied!<p>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)</p> <p>The tables are <strong>Services</strong> and <strong>Checks</strong> (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.</p> <p>The <strong>problem</strong> is, although everything is working fine, I am still getting the error:</p> <blockquote> <p>undefined local variable or method `check_ids'</p> </blockquote> <p>Line:</p> <pre><code>@service.service_checks.build(check_id: check_ids, service_id: @service.id ) </code></pre> <p>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.</p> <p>Models:</p> <pre><code>class Service &lt; ActiveRecord::Base has_many :service_checks, :dependent =&gt; :destroy has_many :checks, :through =&gt; :service_checks #attr_accessor :check_ids accepts_nested_attributes_for :checks accepts_nested_attributes_for :service_checks end class Check &lt; ActiveRecord::Base has_many :service_checks has_many :services, :through =&gt; :service_checks belongs_to :check_cat end class ServiceCheck &lt; ActiveRecord::Base belongs_to :service, dependent: :destroy belongs_to :check, dependent: :destroy accepts_nested_attributes_for :check, :reject_if =&gt; :all_blank self.primary_key = [:service_id, :check_id] end </code></pre> <p>My update function in Service looks like this:</p> <pre><code> 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 =&gt; []) end </code></pre> <p>And my form is simply:</p> <pre><code>&lt;%= f.association :checks, as: :check_boxes, label_method: :name, value_method: :id, label: 'Checks' %&gt; </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload