Ruby on rails 基于连接模型属性的Rails获取对象
如何基于联接模型属性查找对象?鉴于以下情况:Ruby on rails 基于连接模型属性的Rails获取对象,ruby-on-rails,has-many-through,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 Lib
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.joins(:libraries).where(libraries: { :location => locations })
这将连接图书
和库
,并在(1,2)条件下过滤具有库.location的记录
locations = [1,2]
@all_books = Book.joins(:libraries).where("libraries.location in (?)", locations).uniq
我使用的是uniq
,因为当你加入has\u many
relationship时,你会得到同一本书的多条记录。这很好用-看起来它也让我的调用更有效。哦,这很有趣,所以你也可以进行类似sql的查询?
locations = [1,2]
@all_books = Book.joins(:libraries).where("libraries.location in (?)", locations).uniq