2011-11-28 71 views
1

我有2種型號: 用戶和圖書搜索的ActiveRecord通過導軌協會

和聯接模型所有權用於連接用戶和圖書

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協作嗎?

+2

嘗試定義的''Book'是scope'一些'lambda'接收用戶實例或當前用戶得到的書籍。在lambda中,您可以使用普通格式來格式化請求,如連接(:user).where(:users => {:university_id => user.university_id})。 (對Rails 3.1使用[meta_where](https://github.com/ernie/meta_where)或[squeel](https://github.com/ernie/squeel)) –

回答

0

感謝@馬克古克

我最後做的是:

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