2017-05-04 72 views
2

book/show我希望看到它在每個現有庫中的銷售情況,而不會濫用視圖。邏輯可以以某種方式被運送到模型中嗎?當前book/show.hamlrails其他模型方法中的current_model

= @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 
+0

你'Library'缺少'的has_many:sales' – Bohdan

回答

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