Reputation: 7391
When User
object is nil, which is defined in belongs_to association, I get an error: p.user.title
is nil
.
How to check that p.user
or p.user.title
is defined in .map to avoid an error?
@posts = Post.all
results = @posts.map { |p|
{
:id => p.id,
:text => p.text,
:user_title => p.user.title
}
}
Upvotes: 0
Views: 640
Reputation: 44982
You can use the try
method. This will return nil
if the user is nil
@posts = Post.all
results = @posts.map { |p|
{
:id => p.id,
:text => p.text,
:user_title => p.user.try(:title)
}
}
Upvotes: 1
Reputation: 1448
Easy as pie.
p.user.try(:title)
The above runs #title on user if user is not nil.
Upvotes: 2
Reputation: 46675
Simple - just test p.user
before you access title
:
@posts = Post.all
results = @posts.map do |p|
{
:id => p.id,
:text => p.text,
:user_title => p.user && p.user.title
}
end
results[i][:user_title]
will then be nil
if either p.user
or p.user.title
was.
Upvotes: 1