Jack
Jack

Reputation: 3878

Can't access variables in related model

I have a rails app with two models, visits and users. A visit has 2 users; a controller and an engineer. I've set up the relationships as follows, but for some reason I can't access the attributes of the related User. Is this because I am using devise?

Visit Model

class Visit < ActiveRecord::Base
  belongs_to :engineer, :class_name => "User", :foreign_key => 'engineer_id'
  belongs_to :controller, :class_name => "User", :foreign_key => 'controller_id'
end

User Model

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :email, :password, :password_confirmation, :remember_me

  has_many :engineer_visits, :class_name => "Visit", :foreign_key => "engineer_id"
  has_many :controller_visits, :class_name => "Visit", :foreign_key => "controller_id"
end

Visits index view

<% @visits.each do |visit| -%>
  <%= visit.visit_date.strftime("%a %d/%m/%Y") %>
  <%= visit.engineer.email %>
<% end -%>

This is where it fails, with the following exception:

NoMethodError in Visits#index
...
undefined method `email' for nil:NilClass

If I print the <%= debug visit.engineer %> there is an email attribute, but I can't actually get any of the individual attributes to display.

Any ideas on how I can access these variables?

Upvotes: 1

Views: 352

Answers (2)

Batkins
Batkins

Reputation: 5706

Looks to me as though your relationship isn't working properly. Have you tried using the :inverse_of option for your associations?

Example:

class Visit < ActiveRecord::Base
  belongs_to :engineer, :class_name => "User", :foreign_key => 'engineer_id', :inverse_of => :engineer_visits
  belongs_to :controller, :class_name => "User", :foreign_key => 'controller_id', :inverse_of => :controller_visits
end

Also, is there any chance you can name your association something other than controller? Just a hunch but it may be a prohibited variable name in rails due to the fact that controller is a keyword in many of the classes.

Upvotes: 1

Tudor Constantin
Tudor Constantin

Reputation: 26861

Maybe that visit you are getting the error for, is a visit of a controller, not of an engineer.

try modifying your view like:

<% @visits.each do |visit| -%>
  <%= visit.visit_date.strftime("%a %d/%m/%Y") %>
  <%= visit.engineer.email unless visit.engineer.nil? %>
  <%= visit.controller.email unless visit.controller.nil? %>
<% end -%>

Upvotes: 1

Related Questions