Xavier
Xavier

Reputation: 4017

How to display the values of nested attributes in my views ?

I'm starting with Ruby and i got some issue to display the infos in my views.

Here is my code: e app/models/user.rb

class User < ActiveRecord::Base

  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me, :encrypted_password, :meta_attributes

  has_one :meta
  accepts_nested_attributes_for :meta
end

*app/controllers/users_controllers.rb*

  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @users }
    end
  end

app/views/users/index.html.rb

<% @users.each do |user| %>
      <td><%= user.email %></td>
      <td><%= user.meta.last_name %></td>
    <tr>
      <td><%= link_to 'Show', user %></td>
      <td><%= link_to 'Edit', edit_user_path(user) %></td>
      <td><%= link_to 'Destroy', user, method: :delete, data: { confirm: 'Are you sure?' } %></td>
    </tr>
  <% end %>

Has you expected, it returns some errors :

undefined method `last_name' for nil:NilClass

Do you have any clue ?

Upvotes: 1

Views: 1694

Answers (2)

mknarciso
mknarciso

Reputation: 15

I'm pretty sure you've already solved this problem, but i had the same problem here, and solved putting the 'nil' method inside a conditional. Maybe can help someone with the same problem.

<td>
  <% if user.meta %>
    <%= user.meta.last_name %>
  <% end %>
</td>

Upvotes: 0

alestanis
alestanis

Reputation: 21863

The error comes from the line where you use

user.meta.last_name

It means that user.meta is nil.

If you are sure you add a meta to each user while creating them, the problem can come from the fact that meta is not in your attr_accessible list.

If you don't always create a meta for each user and you don't mind about having an empty meta you can add a callback to your User model:

before_create :add_meta

def add_meta
    if self.meta.nil?
        self.meta = Meta.create( put_your_default_attributes_here )
    end
end

Upvotes: 1

Related Questions