按价格范围列出所有书籍

时间:2014-07-09 15:17:55

标签: ruby ruby-on-rails-3 loops group-by range

我创建了一个功能强大的电子商务平台,会员可以在这里买书。一切正常,但我希望按照价格范围将我的所有图书分组到我的索引页面。

目前我可以通过循环列出我的所有图书,但我的代码不是很干。

如何在保持代码干净的同时列出与价格范围相对应的所有图书?

EX of what I need.

Books Under $1 
(.50, .99, .99. .50)

--------------------------

Books Between $1 & $2 
(1.50, 1.99, 1.99. 1.50)

--------------------------

Books Between $2 & $3 
(2.50, 2.99, 2.99. 2.50)

CONTROLLER

class BooksController < ApplicationController

  def index
    @publisher = Publisher.find(params[:publisher_id])
    @books = @publisher.books.where(:ready => true).order("price")
  end

end

模型

class Book < ActiveRecord::Base
  attr_accessible :publisher_id, :price, :ready

end

查看

###This works fine, but can be really repetitive if I have books at a high price.

<% @books.each do |book| %>

  <% if 0 <= book.price && book.price < 1 %>
    Books under $1
  <% end %$> 

  <% if 1 <= book.price && book.price < 2 %>
    Books Between $1 & $2
  <% end %$>

  <% if 2 <= book.price && book.price < 3 %>
    Books Between $2 & $3
  <% end %$>

  <% if 3 <= book.price && book.price < 4 %>
    Books Between $3 & $4
  <% end %$>

<% end %>

2 个答案:

答案 0 :(得分:2)

在您的图书模型中尝试一种方法:

def by_price(low, high)
  self.price.between?(low, high)
end

然后你可以拨打books.by_price(0, 5)并获得介于$ 0和$ 5之间的书籍

答案 1 :(得分:2)

您可以按price.to_i分组以正确分组,然后使用循环将它们全部写入:

<% @books.group_by { |x| x.price.to_i }.each do |low_price, books| %>
  <p>
    Books between $<%= low_price %> and $<%= low_price + 1 %><br/>
    (<%= books.map(&:price).join(', ') %>) <br/>
    --------------------------
  </p>
<% end %>