2015-03-31 69 views
0

使用領域在我的Rails 4應用程序,我有一個像模特獅身人面像過濾器:軌道4 - 思考對相關模型

'AgencyGroup'

has_many :group_agencies 
has_many :agencies, :through => :group_agencies 

如果我保持 '令牌' 字段

「代理」的模式

has_many :group_agencies 
    has_many :agency_groups, :through => :group_agencies 
    has_many :advertisements 

'廣告' 的模式

belongs_to :agency 

我使用思維獅身人面像,它的工作真的很大,但現在我得到了新的要求,通過AgencyGroup標記字段篩選'廣告'。

基本上我需要找到一些參數的廣告,但只適用於代理組中的代理人張貼令牌。

if params[:search] 
@results = Advertisement.search Riddle::Query.escape(params[:search]), :star => true, :page => params[:page], :per_page => 6 
end 

爲了得到結果我跑HTTP查詢是這樣的:

http://api.localhost.local:3000/v1/advertisements?token=JHW_tdXn5g-vQY1f_ZzLuw&search=Nissim 

什麼我失蹤?如何使用TS中的模型之間的關係?

回答

0

我覺得這裏最好的辦法涉及幾個步驟:

步驟1:添加AgencyGroup ID作爲你們的廣告索引的屬性。如果您使用SQL支持指數(:with => :active_record),這是一個班輪:

has agency.group_agencies.agency_group.id, :as => :agency_group_ids 

如果您使用實時指數,那麼你會希望在廣告的方法返回所有那些編號:

def agency_group_ids 
    agency.agency_group_ids 
end 

而且你的屬性定義看起來就像這樣:

has agency_group_ids, :type => :integer, :multi => true 

步驟2:因爲你已經改變了你的索引結構,不要忘了重建索引:

# for SQL-backed indices: 
rake ts:rebuild 
# or, for real-time indices 
rake ts:regenerate 

第3步:在您的控制器,找到該機構組給定的令牌:

agency_group = AgencyGroup.find_by :token => params[:token] 

第4步:最後,用該代理組的ID在您的搜索電話中:

@results = Advertisement.search Riddle::Query.escape(params[:search]), 
    :star  => true, 
    :page  => params[:page], 
    :per_page => 6, 
    :with  => {:agency_group_ids => agency_group.id} 
+0

太棒了!完美的作品。非常感謝您的回答。乾淨簡單的解決方案。完善。 – rolkos 2015-04-02 11:55:51