Ruby on rails 简单问题

Ruby on rails 简单问题,ruby-on-rails,Ruby On Rails,我有一对多的用户关联我认为你的语法没有意义。尝试: post.user.email if post.user_id? 或 或 或 所有这些都应该有效。注意:您还应该能够使用post.user.present?或!post.user.nil?这两个选项看起来都比检查id更干净。您应该能够稍微重新表述一下,以便它更有意义: <%= post.user.email if post.user %> 我不太理解您的代码,因为它看起来不像您发布的条件,但上面的ERB语句应该可以做到这一点

我有一对多的用户关联我认为你的语法没有意义。尝试:

post.user.email if post.user_id?


所有这些都应该有效。注意:您还应该能够使用
post.user.present?
!post.user.nil?
这两个选项看起来都比检查id更干净。

您应该能够稍微重新表述一下,以便它更有意义:

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

我不太理解您的代码,因为它看起来不像您发布的条件,但上面的ERB语句应该可以做到这一点

编辑:我应该补充一点,Ruby在条件语句中将nil对象计算为false,因此不需要检查
user.nil?
,尽管这仍然是完全有效的。这使您可以像上面的语句一样做出简短、简单的条件语句

post.user.email if post.user_id?
post.user_id? ? post.user.email : nil
if post.user_id?
    post.user.email
end
post.user.try(:email)
<%= post.user.email if post.user %>