erb:how to filter on resource attribute

时间:2019-01-18 18:45:00

标签: ruby-on-rails

How can I filter the results based on the resource attribute in .erb file. For example, I would like to display product which price is lower than 50 dollars. The following is current .erb file. The price tag is a string, need to be converted to number.

    <% @products.each do |product| %>
    <tr>
    <td><%= product.title %></td>
    <td><%= product.price %></td>
    <td><%= product.count %></td>
    </tr>
    <% end %>

Can I use this in the view? I have undefined method "filter" error.

       <% @products.filter { |p| p.price < 50 }.each %>
       <tr>
       <td><%= product.title %></td>
       <td><%= product.price %></td>
       <td><%= product.count %></td>
       </tr>
       <% end %>

1 个答案:

答案 0 :(得分:0)

简短的回答:您可以使用select仅选择价格低于50美元的产品,甚至可以使用partition将列表拆分为低于和高于该价格的产品。 理想情况下,您可以在视图外部执行此操作,例如在控制器甚至模型内部。

基本过滤(内部视图):

@products.select { |p| p.price < 50 }.each do |product|

或在模型中包含范围:

scope :below_price, ->(price) { where("price < ?", price) }

您可以在控制器中使用它:

PRICE_THRESHOLD = 50

def index
  @products = Product.below_price(PRICE_THRESHOLD)
end