我创建了一个运作良好的电子商务平台,会员可以在这里购买/查看书籍。一切正常,但我想通过Book_Id组织我的索引页面中的所有书籍。
目前,我有3个阵列根据图书可用性和会员购买或未购买的图书显示不同的信息。如何组合这些数组,或者按BOOK_ID组织它们。
实施例
Total Books = 10
5 Available Books {1, 2, 3, 4, 5}
3 Books Purchased {6, 8, 9}
2 Coming Soon Books {7, 10}
Can I somehow organize the arrays by id {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
模型
class User < ActiveRecord::Base
attr_accessible :name, :email, :password, :member
has_many :books, through: :orders
has_many :orders, :dependent => :destroy
###Users purchased books
def purchased_books
books
end
def unavailable_unpurchased_books
Book.unavailable.where("id not in (?)", purchased_issues.pluck(:issue_id))
end
end
class Order < ActiveRecord::Base
attr_accessible :book_id, :order_date, :user_id
belongs_to :publisher
belongs_to :user
belongs_to :book
end
class Book < ActiveRecord::Base
attr_accessible :publisher_id, :description, :pages, :title, :available_in, :price, :release_date
has_many :orders
has_many :users, through: :orders
scope :unavailable,->{where("release_date > ?",Date.today)}
scope :available,->{where("release_date < ?",Date.today)
end
CONTROLLER
def index
@available_books = Book.available.where(:publisher_id => @publisher.id)
@orders = current_user.orders
respond_to do |format|
format.html
format.json { render :json => @issues }
end
end
视图
<% if current_user.member? %>
###HOW CAN I ORGANIZE THESE INTO 1 BY BOOK_ID
###Shows All Available Books
<% @available_books.each do |book| %>
<%= book.title %>
<% end %>
###Shows Books Bought By Member
<% @orders.each do |order| %>
<%= order.book.title %>
<% end %>
###Shows All Books Not Available or Coming Soon
<% current_user.unavailable_unpurchased_books do |book| %>
<%= book.title %>
<% end %>
<% end %>
答案 0 :(得分:1)
未经测试,但如何......
...控制器
@available_books = Book.available.where(:publisher_id => @publisher.id)
@ordered_books = current_user.books
@not_available = current_user.unavailable_unpurchased_books
@all_books = @available_books + @ordered_books + @not_available
@all_books.sort!{|x| x.id}
您可能需要一些辅助方法来显示哪些图书在视图中的哪些类别