Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.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
Sql 活动记录:使用“连接查询”;其中;条款_Sql_Ruby On Rails_Activerecord_Join - Fatal编程技术网

Sql 活动记录:使用“连接查询”;其中;条款

Sql 活动记录:使用“连接查询”;其中;条款,sql,ruby-on-rails,activerecord,join,Sql,Ruby On Rails,Activerecord,Join,这是我的模型: 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

这是我的模型:

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
但我还想添加一些基于参数的where查询


我怎样才能做到这一点呢?

您应该使用
连接

Book.joins('LEFT OUTER JOIN rentals ON books.id = rentals.book_id')
    .where('rentals.return_date IS NULL')

joins
方法将用于左外部联接,但您需要自己构造SQL片段。下面,结合
合并
和额外的租赁范围,演示了这一点

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

但是用这种方式它会做一个内部连接,我需要一个外部连接。因此,我可以列出每一本没有归还日期的租赁书籍和从未租赁过的书籍。@DavidAnderson查看我的编辑,您可以使用带有
连接的外部连接。
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
def pending?
  return_date.nil?
end