0

我试图在我的网站上显示一个用户数据表 - 所以我正在使用一个循环来遍历用户并显示他们的信息。以前,这真的很简单,但我想添加条件来处理可能没有城市、州或任何一个输入的情况。当我只输入一个案例时,它工作正常。当我两者都有时,它工作正常。用户位置在模型中定义为城市和州的 JOIN。所以不用担心。但是当我两者都没有时,它不会显示我想要的'---'。我在这里想念什么?

<tr>
  <% @user.each do |user| %>
    <td><%= link_to user.username, public_profile_path(user.username) %><br/></td>

    <% if user.state != nil and user.city != nil %>
      <td><%= user.location %></td>
    <% elsif user.state != nil and user.city == nil %>
      <td><%= user.state %></td>
    <% elsif user.state == nil and user.city != nil %>
      <td><%= user.city %></td>
    <% else %>
      <td>---</td>
    <% end %>

    <% if user.phone != nil %>
      <td><%= user.phone %></td>
    <% else %>
      <td>-</td>
    <% end %>

    <td><%= mail_to user.email.to_s, "Email this User", :cc => "michaelomchenry@gmail.com",
        :subject => "Contact from Overflow Member" %></td> 

  </tr>
<% end %>
4

1 回答 1

3

我会添加一个辅助方法,称为 location_display 或类似的方法来处理应显示的所有逻辑。

def location_display(user)
  return user.location if user.state && user.city
  return user.state if user.state && user.city.blank?
  return user.city if user.city && user.state.blank?
  "----"
end

然后,在您看来,只需将所有这些行替换为:

  <td><%= location_display(user) %></td>
于 2013-03-26T20:23:22.307 回答