Ruby on rails 其他模型方法中的rails当前_模型
在Ruby on rails 其他模型方法中的rails当前_模型,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,在book/show中,我希望在不滥用视图的情况下查看每个现有图书馆的销售情况。逻辑是否可以以某种方式传输到模型中?当前book/show.haml: = @book.name - @libraries.each do |library| = library.sales.where(book_id: @book.id).map(&:quantity).sum 我的想法是在library.rb中添加一个方法,如: def current_book_sold_by_
book/show
中,我希望在不滥用视图的情况下查看每个现有图书馆的销售情况。逻辑是否可以以某种方式传输到模型中?当前book/show.haml
:
= @book.name
- @libraries.each do |library|
= library.sales.where(book_id: @book.id).map(&:quantity).sum
我的想法是在library.rb中添加一个方法,如:
def current_book_sold_by_library
@book = Book.find(:id)
#sales.where(book_id: @book.id).map(&:quantity).sum
sales.map(&:quantity).sum
end
但玩这个也没用。我的设置:
book.rb:
class Book < ActiveRecord::Base
end
classbook
library.rb
class Library < ActiveRecord::Base
has_many :books, through: :sales
end
类库
sale.rb
class Sale < ActiveRecord::Base
belongs_to :book
belongs_to :library
end
class Sale
books_controller.rb
class BooksController < ApplicationController
def show
@libraries = Library.all
@sales = @book.sales
end
end
class BooksController
您可以将一本书作为参数添加到库
模型中:
# view
- @libraries.each do |library|
= library.book_sold_by_library(@book)
# Library model
def book_sold_by_library(book)
sales.where(book_id: book.id).map(&:quantity).sum
end
您的库
缺失有许多:销售