Reputation: 380
i just get an error.
i got a has many assotiations, but when filling a form, i leave the field empty, and ir returned me an error:
Showing /home/techmago/namebook/app/views/names/index.html.erb where line #16 raised:
undefined method `nome' for nil:NilClass
Extracted source (around line #16):
13: <% @names.each do |name| %>
14: <tr>
15: <td><%= name.nome %></td>
16: <td><%= name.family.nome %></td>
17: <td><%= name.race.nome %></td>
18: <td><%= h(name.descr).gsub(/\n/, '<br/>').html_safe %></td>
19: <td>
I am sure that is because one of the name.family.nome is nill. I would like that this situation could be accepted
Models:
class Name < ActiveRecord::Base
belongs_to :family
belongs_to :race
has_and_belongs_to_many :books
attr_accessible :descr, :family_id, :nome, :race_id, :book_ids
validates :nome, presence: true
end
class Family < ActiveRecord::Base
has_many :names
has_and_belongs_to_many :books
has_and_belongs_to_many :races
attr_accessible :descr, :nome, :book_ids, :race_ids
validates :nome, uniqueness: true, presence: true
end
Upvotes: 0
Views: 317
Reputation: 18037
So what we know is that that name
, in particular, doesn't have an associated family
object. That is, name.family
is returning nil
, which doesn't respond to nome
, as indicated by the error. So, if what you're looking for is that this be handled gracefully... i.e. don't error and don't show anything in this case, you can do this:
<%= name.family.try(:nome) %>
The try
block will return nil
if name.family
is nil
and then the erb block will return an empty string, basically.
Otherwise, you'll need to figure out why one of the name
s in the loop doesn't have a family
and go from there.
Upvotes: 2