开发者

Rails View : Idiomatic way to show description for an association object that can be null?

开发者 https://www.devze.com 2023-02-22 04:10 出处:网络
Model Member belongs_to Discipline, i.e. user can have a discipline but it is optional. I\'m wondering what would be the idiomatic Rails way to show member\'s discipline when I show the user details.

Model Member belongs_to Discipline, i.e. user can have a discipline but it is optional.

I'm wondering what would be the idiomatic Rails way to show member's discipline when I show the user details.

My first approach

<b>Discipline:</b>
<%=h @member.discipline.name %>

works otherwise fine but fails with NoMethodError if member's discipline is Nil. In that case, I'd like to have nothing there.

A couple of alternatives I have are

  • Define method Member:discipline_name that returns "" if member doesn't have a discipline
  • Restrict output with if;

The alternative with "if" would be something like:

<b>Discipline:<开发者_JAVA技巧;/b>
<% if @member.discipline %>
<%=h @member.discipline.name %>
<% end %>

This isn't a big decision to make but I'd like to know if there's an "idiomatic way" to do this or some helper/something or something else to consider.

br, Touko


In my opinion the idiomatic way would be:

<b>Discipline:</b>
<%=h @member.discipline.name if @member.displince.present? %>


Actually, developing Wukerplank's answer further, following seems to work fine and be pretty concise:

<b>Discipline:</b>
<%=h @member.discipline.name if @member.discipline %>


If you need to display anything in case of non-existence, you can use the ternery operator:

<%= condition ? statement true : statement false %>

<%= @member.discipline ? @member.discipline.name : 'none' %>
0

精彩评论

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