通过rails关联搜索ActiveRecord



我有两个模型:用户和图书

和连接User和Book的连接模型所有权

class Book < ActiveRecord::Base
  has_many :ownerships
  has_many :users, :through => :ownerships,:uniq=>true
  ...
end
class User < ActiveRecord::Base
  has_many :ownerships
  has_many :books, :through => :ownerships
end
class Ownership < ActiveRecord::Base
  belongs_to :user
  belongs_to :book
end

这个场景是,当用户A在我的网站上搜索图书时,我返回用户A周围的用户拥有的相关图书(例如,他们都在同一所大学)。

我可以用rails关联吗?

感谢@Mark Guk

我最后做的是:

  scope :same_university,lambda{|q,current_user|
    where("title like '%#{q}%'").joins(:sell_infos).where(
      "sell_infos.university is '#{current_user.university}'")
  }

最新更新