2

テーブルに次の<tr>タグがあります

<% if user.company.nil? %>
  <tr class="error">
<% else %>
  <tr>
<% end %>
  <td><%= user.name %></td>
</tr>

別の if 文を追加したい

<% if user.disabled? %>
  <tr class="disabled">
<% end %>

したがって、このステートメントのうちの 2 つtrueを受け取る場合は、次のようにします。

<tr class="error disabled">

それをヘルパーに移動する必要があることはわかっていますが、このステートメントに依存するクラスを拡張するための適切なケースステートメントを作成する方法は?

4

2 に答える 2

2
def tr_classes(user)
  classes = []
  classes << "error" if user.company.nil?
  classes << "disabled" if user.disabled?
  if classes.any?
    " class=\"#{classes.join(" ")}\""
  end
end

<tr<%= tr_classes(user) %>>
  <td><%= user.name %></td>
</tr>

しかし、良いスタイルは次のとおりです。

def tr_classes(user)
  classes = []
  classes << "error" if user.company.nil?
  classes << "disabled" if user.disabled?
  if classes.any?   # method return nil unless
    classes.join(" ")
  end
end

<%= content_tag :tr, :class => tr_classes(user) do -%> # if tr_classes.nil? blank <tr>
  <td><%= user.name %></td>
<% end -%>
于 2012-12-25T02:17:21.800 に答える
0

あなたは次のようなヘルパーメソッドを試すことができます

def user_table_row(user)
  css = ""
  css = "#{css} error" if user.company.nil?
  css = "#{css} disabled" if user.disabled?

  content_tag :tr, class: css
end

テーブル行の場合、tdをその中にネストする必要があるため、これがどの程度うまく機能するかわかりません。

更新:ここに更新されたバージョンがあり、tdコードのブロックが生成されます

def user_table_row(user)
  css = # derive css, using string or array join style

  options = {}
  options[:class] = css if css.length > 0

  content_tag :tr, options do
    yield
  end
end

その後、ビューで

<%= user_table_row(user) do %>
  <td><%= user.name %></td>
<% end %>
于 2012-12-25T02:13:46.823 に答える