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?
Maybe that visit you are getting the error for, is a visit of a controller, not of an engineer.
try modifying your view like: