开发者

Simple Rails question

I have a one-to-many association of Users<-Posts.

Some Posts are associated, others have a user_id of nil.

If, in ERB, I do:

post.user_id? po开发者_开发百科st.user.email

I get a

undefined method `email' for nil:NilClass

when iterating over Posts. Why does my initial conditional not protect against this?


I don't think your syntax makes sense. Try:

post.user.email if post.user_id?

or

post.user_id? ? post.user.email : nil

or

if post.user_id?
    post.user.email
end

or

post.user.try(:email)

All of those should work. Note: you should also be able to use post.user.present? or !post.user.nil? which both seem cleaner than checking the id.


You should be able to rephrase that slightly so that it makes more sense:

<%= post.user.email if post.user %>

I don't quite understand your code, as it doesn't look like a conditional from what you posted, but the above ERB statement should do the trick.

Edit: I should add that Ruby evaluates a nil object to false in a conditional statement, so there's no need to check for user.nil?, although that is still perfectly valid. That allows you to make short, simple conditional statements like the one above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜