Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/.htaccess/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 其他模型方法中的rails当前_模型_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

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

您的
缺失
有许多:销售