Rails基于连接模型属性获取对象

时间:2014-03-13 15:41:07

标签: ruby-on-rails has-many-through

如何根据连接模型属性查找对象?鉴于以下内容:

class Book < ActiveRecord::Base
  has_many :libraries
  has_many :renters, :through => :libraries
end

class Renter < ActiveRecord::Base
  has_many :libraries
  has_many :books, :through => :libraries
end

class Library < ActiveRecord::Base
  belongs_to :renter
  belongs_to :book

  # model has a location:integer property
end

我如何使用以下伪代码进行搜索:

locations = [1,2]
@all_books = Book.where(:location => locations)

2 个答案:

答案 0 :(得分:1)

您需要加入这两个表。尝试:

locations = [1,2]
@all_books = Book.joins(:libraries).where(libraries: { :location => locations })

这会加入bookslibraries,并使用libraries.location in(1,2)条件过滤记录。

答案 1 :(得分:1)

locations = [1,2]
@all_books = Book.joins(:libraries).where("libraries.location in (?)", locations).uniq

我正在使用uniq,因为当您加入has_many关系时,您将获得同一本书的多条记录