{"id":861,"date":"2022-08-30T15:08:24","date_gmt":"2022-08-30T15:08:24","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2013\/11\/09\/rails-3-undefined-method-nilnilclass-has_many-through-when-attempting-create-collection-of-common-programming-errors\/"},"modified":"2022-08-30T15:08:24","modified_gmt":"2022-08-30T15:08:24","slug":"rails-3-undefined-method-nilnilclass-has_many-through-when-attempting-create-collection-of-common-programming-errors","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2022\/08\/30\/rails-3-undefined-method-nilnilclass-has_many-through-when-attempting-create-collection-of-common-programming-errors\/","title":{"rendered":"Rails 3 undefined method nil:NilClass has_many :through when attempting create-Collection of common programming errors"},"content":{"rendered":"<p>I am encountering a problem when trying to .build a new appointment. But first a look at my Model(s)<\/p>\n<pre><code>class Patient &lt; ActiveRecord::Base\n  attr_accessible :address1, :address2, :city, :comment, :email, :first_name, :init_date,    :init_time, :last_name, :mobile, :notes, :phone, :state, :zip\n  before_validation :upcase_patient\n  before_save { self.email.downcase! }\n  has_many :appointments, dependent: :destroy\n  has_many :procedures, through: :appointments\n<\/code><\/pre>\n<pre><code>class Procedure &lt; ActiveRecord::Base\n  attr_accessible :comment, :occurence, :procedure, :procedure_code, :procedure_price, :procedure_time, :visits\n  before_validation :uppercase_procedure\n  has_many :appointments\n  has_many :patients, through: :appointments\n<\/code><\/pre>\n<pre><code>class Appointment &lt; ActiveRecord::Base\n  attr_accessible :appointment_date, :appointment_notes, :appointment_time, :procedure_id\n  belongs_to :patient\n  belongs_to :procedure\n<\/code><\/pre>\n<pre><code>class AppointmentsController &lt; ApplicationController\ninclude PatientsHelper\nbefore_filter :signed_in_user\n\ndef create\n    @patient = current_patient\n    @appointment = @patient.appointments.build(params[:appointment])\n    if @appointment.save\n        flash[:success] = \"Appointment scheduled!\"\n        redirect_to patient_path(@patient)\n    else\n        render patient_path(@patient)\n    end\nend\n<\/code><\/pre>\n<pre><code>module PatientsHelper\n\n    def current_patient=(patient)\n            @current_patient = patient\n    end\n\n    def current_patient\n            @current_patient\n    end\n\n    def current_patient?(patient)\n            patient == current_patient\n    end\nend\n<\/code><\/pre>\n<p>These items including &#8220;PatientsHelper&#8221; which helps define current_patient make up the associations. I have created the form successfullly within the patients_controller<\/p>\n<pre><code>class PatientsController &lt; ApplicationController\nbefore_filter :signed_in_user\nbefore_filter :admin_user, only: [:destroy]\ndef show\n    @patient = Patient.find(params[:id])\n    @procedures = Procedure.all\n    @appointments = @patient.appointments.paginate(page: params[:page])\n    @appointment = @patient.appointments.build\nend\n<\/code><\/pre>\n<p>I would like to use the patients resources to create new appointments. Here is where I am fouled up. I continue to receive via rspec the following error:<\/p>\n<pre><code>NoMethodError:\n   undefined method `appointments' for nil:NilClass\n<\/code><\/pre>\n<p>Where am I going wrong? Any help would be greatly appreciated. If clarification is required, I would like to:<\/p>\n<p>a_ associate<\/p>\n<p>Patient model -&gt; has_many [:appointments, :procedures (through :appointments)]<\/p>\n<p>Procedure model -&gt; has_many [:appointments, :patients (through :appointments)]<\/p>\n<p>Appointment model -&gt; belongs_to [:patients, :procedures]<\/p>\n<p>b_ create new :appointments through the patients controller rather than create a new controller specifically for appointments model<\/p>\n<p>my mistake! here is the spec test.<\/p>\n<pre><code>require 'spec_helper'\n\ndescribe \"Appointment Pages\" do\n    subject { page }\n\n    let(:user) { FactoryGirl.create(:user) }\n    let(:patient) { FactoryGirl.create(:patient) }\n    let(:procedure) { FactoryGirl.create(:procedure) } \n    before { sign_in user }\n\n    describe \"appointment creation\" do\n  before { visit patient_path(patient) }\n\n  describe \"with invalid information\" do\n\n    it \"should not create an appointment\" do\n        expect { click_button \"Schedule procedure\" }.not_to change(Appointment,\n                                                                                                                             :count)\n    end\n\n    describe \"error messages\" do\n        before { click_button \"Schedule procedure\" }\n        it { should have_content('error') }\n    end\nend\n\ndescribe \"with valid information\" do\n    before do\n      procedure_id = procedure.id\n      patient_id = patient.id\n      fill_in 'appointment_appointment_date', with: \"2013-04-04\"\n      fill_in 'appointment_appointment_time', with: \"12:45:00\"\n      fill_in 'appointment_appointment_notes', with: \"Test the notes\"\n    end\n    it \"should create a micropost\" do\n        expect { click_button \"Schedule procedure\" }.to change(Appointment, \n                                                                                                                    :count).by(1)\n      end\n    end\n  end\nend\n<\/code><\/pre>\n<p>errors show up on the following<\/p>\n<pre><code>Failures:\n\n1) Appointment Pages appointment creation with invalid information should not create an appointment\n Failure\/Error: expect { click_button \"Schedule procedure\" }.not_to change(Appointment,\n NoMethodError:\n   undefined method `appointments' for nil:NilClass\n # .\/app\/controllers\/appointments_controller.rb:7:in `create'\n # (eval):2:in `click_button'\n # .\/spec\/requests\/appointment_pages_spec.rb:17:in `block (5 levels) in '\n # .\/spec\/requests\/appointment_pages_spec.rb:17:in `block (4 levels) in '\n\n2) Appointment Pages appointment creation with invalid information error messages \n Failure\/Error: before { click_button \"Schedule procedure\" }\n NoMethodError:\n   undefined method `appointments' for nil:NilClass\n # .\/app\/controllers\/appointments_controller.rb:7:in `create'\n # (eval):2:in `click_button'\n # .\/spec\/requests\/appointment_pages_spec.rb:22:in `block (5 levels) in '\n\n3) Appointment Pages appointment creation with valid information should create a micropost\n Failure\/Error: expect { click_button \"Schedule procedure\" }.to change(Appointment,\n NoMethodError:\n   undefined method `appointments' for nil:NilClass\n # .\/app\/controllers\/appointments_controller.rb:7:in `create'\n # (eval):2:in `click_button'\n # .\/spec\/requests\/appointment_pages_spec.rb:36:in `block (5 levels) in '\n # .\/spec\/requests\/appointment_pages_spec.rb:36:in `block (4 levels) in '\n\nFinished in 1.08 seconds\n23 examples, 3 failures\n\nFailed examples:\n\nrspec .\/spec\/requests\/appointment_pages_spec.rb:16 # Appointment Pages appointment creation with invalid information should not create an appointment\nrspec .\/spec\/requests\/appointment_pages_spec.rb:23 # Appointment Pages appointment creation with invalid information error messages \nrspec .\/spec\/requests\/appointment_pages_spec.rb:35 # Appointment Pages appointment creation with valid information should create a micropost\n<\/code><\/pre>\n<ol>\n<li>\n<p>Not exactly what I was looking for but made this work-around.<\/p>\n<p>Using the following was able to get this to save accordingly. <em>Still cannot find out why I am unable to pull the Patient from the URL &#8212; example would be app.dev\/patients\/2 &#8212; where patient information is pulling id 2<\/em>&#8230; but now I am able to save the Appointment using what I suspect is a rather crude method.<\/p>\n<ol>\n<li>In the form I added a hidden field which pulls the appropriate patient_id<\/li>\n<li>In Appointments controller, added to attr_accessible :patient_id<\/li>\n<li>\n<p>In appointments_controller<\/p>\n<pre><code>def create\n@appointment = Appointment.new(params[:appointment])\n@current_patient = @appointment.patient_id\nif @appointment.save\n    flash[:success] = \"Appointment scheduled!\"\n    redirect_to patient_path(@current_patient)\nelse\n    render 'patients\/show'\nend\nend\n<\/code><\/pre>\n<\/li>\n<\/ol>\n<p><code>render 'patients\/show'<\/code> remains broken but will leave that for another thread. Thank you all for your help and guidance.<\/p>\n<\/li>\n<\/ol>\n<p id=\"rop\"><small>Originally posted 2013-11-09 22:49:22. <\/small><\/p>","protected":false},"excerpt":{"rendered":"<p>I am encountering a problem when trying to .build a new appointment. But first a look at my Model(s) class Patient &lt; ActiveRecord::Base attr_accessible :address1, :address2, :city, :comment, :email, :first_name, :init_date, :init_time, :last_name, :mobile, :notes, :phone, :state, :zip before_validation :upcase_patient before_save { self.email.downcase! } has_many :appointments, dependent: :destroy has_many :procedures, through: :appointments class Procedure &lt; [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-861","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/861","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=861"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/861\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=861"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=861"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=861"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}