Neon_10
Neon_10

Reputation: 731

Undefined method `name' for nil:NilClass for a property from a joined table

I have a quick question. I have 2 tables: Books and Readers. They are joined like this:

class Book < ActiveRecord::Base
 belongs_to :reader
end

class Reader < ActiveRecord::Base
 has_many :books
end

So, in the database I have one book which has a assigned reader, and in the view I have such line in a block:

<td><p><%= book.reader.name %></p></td>

But it says there is an error undefined method name for nil:NilClass, although if I change it with

<td><p><%= book.reader %></p></td>

it shows me an address of the object: Reader:0x007fa60ea72f40

Please could you advise me what is going on here? As I suppose it should show a Reader's name as a result...

the schema of my model is:

ActiveRecord::Schema.define(version: 20150320182921) do

  create_table "books", force: :cascade do |t|
    t.string   "name"
    t.string   "author"
    t.integer  "pages"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.integer  "reader_id"
 end

  create_table "readers", force: :cascade do |t|
    t.string   "name"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

end

Upvotes: 0

Views: 812

Answers (2)

Arup Rakshit
Arup Rakshit

Reputation: 118271

You can get rid on this using the use try method. You probably have some books without authors, and that's the reason when you are calling book.author, you are getting nil, on which when you are calling name method. That's causing the NoMethodError exception. Try to write it using

<%= book.author.try(:name) %>

Upvotes: 2

Sharvy Ahmed
Sharvy Ahmed

Reputation: 7405

undefined method `name' for nil:NilClass

I think you have some books with no reader associated. So when you are trying to access name attribute of a nil reader, it is getting exception.

So it would be nice to rescue the nil using #try, try returns nil when called on nil:

<% @books.each do |book| %>
  <%= book.reader.try(:name) %>
<% end %>

Upvotes: 1

Related Questions