2009-04-28 50 views
0

第一次嘗試與獅身人面像/思維獅身人面像相處融洽。思維獅身人面像 - RuntimeError:缺少外鍵屬性

我有如下定義(簡體)我的模型:

class Branch < ActiveRecord::Base 
    has_many :salesmen, :class_name => "User" 
    has_many :leads, :through => :salesmen 
end 

class User < ActiveRecord::Base 
    belongs_to :branch 
    has_many :leads, :foreign_key => "owner_id" 
end 

class Lead < ActiveRecord::Base 
    belongs_to :owner, :class_name => "User" 

    define_index do 
    indexes company_name  
    indexes :name, :sortable => true 
    has owner.branch_id, :as => :branch_id 
    indexes [owner.last_name, owner.first_name], :as => :owner_full_name, :sortable => true 
    end 

end 

每當我打電話

Branch.first.leads.search 

我得到

RuntimeError: Missing Attribute for Foreign Key branch_id 

我在做什麼錯?

回答

3

問題是思考獅身人面像需要branch_id爲索引中的一個屬性,因此它可以將結果限制爲只相關分支(因爲你是一個羣內搜索)。

從您的關聯(或者也許只是我非常需要睡眠)中,不管是通過所有者還是屬於某個分支,還是直接也不清楚。如果前者,本的建議可能是正確的。否則,請嘗試添加以下到您的define_index塊:

has branch_id, :as => :direct_branch_id 

的另一種方法,閱讀評論後,對自己的搜索方法添加到科引線關聯。一個模糊的嘗試(你需要調試,我敢肯定):

has_many :leads, :through => :salesmen do 
    def search(*args) 
    options = args.extract_options! 
    options[:with] ||= {} 
    options[:with][:branch_id] = proxy_owner.id 
    args << options 
    Lead.search(*args) 
    end 
end 

這應該得到迴避的事實,你沒有直接引用來自鉛分支。唯一可能的問題是,我不確定自定義擴展是在思考獅身人面像注入之前還是之後加載的。試試看,看看它是否有幫助。

0

我相信你在分支關係中缺少a:through選項。嘗試更新到:

class Lead < ActiveRecord::Base 
    has_one :branch, :through => :owner 
+0

恐怕:通過不是belongs_to協會的有效選項。據我所知。 – 2009-04-28 21:07:07

+0

對不起,我的意思是改變爲一個關係。現在更新我的答案! – Ben 2009-04-29 13:22:00

+0

不幸的是,由於所有者belongs_to分支並且has_one:branch,:through =>:owner不會給我任何東西,只有一個例外。 – 2009-04-29 14:31:03

0

如果您說一個潛在客戶belongs_to一個分支,那麼您必須在潛在客戶表中有一個branch_id。既然你沒有,這不是一個belongs_to的關係。我認爲你需要這樣的事情:

class Branch < ActiveRecord::Base 
    has_many :leads, :through => :salesmen 
    has_many :salesmen, :class_name => "User" 
end 

class User < ActiveRecord::Base 
    belongs_to :branch # users table has branch_id 
    has_many :leads, :foreign_key => "owner_id" 
end 

class Lead < ActiveRecord::Base 
    belongs_to :owner, :class_name => "User" # leads table has owner_id 

    define_index do 
    indexes :company_name  
    indexes :name, :sortable => true 
    has owner.branch_id, :as => :branch_id 
    indexes [owner.last_name, owner.first_name], :as => :owner_full_name, :sortable => true 
    end 

end