Robert B
Robert B

Reputation: 2883

Problem access relationship data in view - Rails 3

I have a site which has members with a has_one relationship to their profile.

I want to display some of their member profile information in the admin dashboard I've created.

In the rails console I can access the information using:

member = Member.find(1)
member.profile.first_name

In my controller

def index
    @members = Member.all
end

In my admin view I have

<% @members.each do |member| %>
    <p><%= member.id %></p>
    <p><%= member.profile.first_name %></p>
<% end %>

except this raise an undefined method error

undefined method `first_name' for nil:NilClass

How can I access the profile information in my view?

Upvotes: 1

Views: 508

Answers (1)

rubyprince
rubyprince

Reputation: 17793

I think some of your members do not have a profile associated with it. To prevent the error, you can do something like this:

<% @members.each do |member| %>
    <p><%= member.id %></p>
    <p><%= member.profile ? member.profile.first_name : "-" %></p>
<% end %>

UPDATE:

You are better off including profile in the controller itself, in order to prevent N + 1 query problem. You can do this in the controller:

def index
  @members = Member.includes(:profile)
end

Upvotes: 4

Related Questions