rails current_model在其他模型方法中

时间:2017-05-04 23:32:15

标签: 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_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

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

books_controller.rb

class BooksController < ApplicationController
  def show
    @libraries = Library.all
    @sales = @book.sales
  end
end

1 个答案:

答案 0 :(得分:3)

您可以将一本书作为参数添加到Library模型:

# 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