-1

这是我的模型:

class Book < ActiveRecord::Base
    attr_accessible :author, :title
    validates :author, presence: true
    validates :title, :uniqueness => true, presence: true

    has_many :rentals 

    def rent?
        rentals.where(return_date: nil).count > 0
    end
end

class Rental < ActiveRecord::Base
    belongs_to :student
    belongs_to :book

    validates :student, presence: true
    validates :book, presence: true
    validates :rental_date, presence: true

    attr_accessible :rental_date, :return_date, :student, :book

    def pending?
        return return_date == nil
    end

    def overdue?
        if(return_date)
            return_date - rental_date > 7.days
        else
            Time.now - rental_date > 7.days
        end
    end
end

我想查询所有不在租借中的书(即没有return_date 的这本书没有租借)。

我以为我可以使用我的“租金”?方法,但我无法使其工作,所以我尝试加入。

这就是我得到的:

Book.includes(:rentals).find(:all, :conditions => ['"rentals"."return_date" is NULL'])

但我还想根据我的参数添加一些 where 查询。

我怎样才能做到这一点?

4

2 回答 2

2

joins方法适用于左外连接,但您需要自己构建 SQL 片段。下面,这被演示,结合一个merge和一个额外的租赁范围。

class Rental < ActiveRecord::Base
  scope :no_return, where('return_date IS NULL')
end

join_statement = 'LEFT OUTER JOIN rentals ON rentals.book_id = books.id'
Book.joins(join_statement).merge(Rental.no_return)
# => returns set of books with no rentals and 
# books with rentals that have no return date

在不相关的注释中,您会发现许多人更喜欢这样编写您的pending?方法:

def pending?
  return_date.nil?
end
于 2013-04-23T02:33:14.587 回答
1

你应该使用joins

Book.joins('LEFT OUTER JOIN rentals ON books.id = rentals.book_id')
    .where('rentals.return_date IS NULL')
于 2013-04-23T00:30:19.337 回答