2014-06-18 23 views
0

我有兩個型號,用戶和帳戶:belongs_to的有:條件的Rails 4

class User < ActiveRecord::Base 
    belongs_to :account, :conditions=>proc{" company_account = #{self.company_user} "} 
end 

class Account < ActiveRecord::Base 
    has_many :users 
end 

在Rails 3 belongs_to:conditions=>工作正常,但在Rails的4我看了這個選項是無效的。

我試圖belongs_to :account, -> {where company_account: self.company_user}但我得到錯誤undefined methodcompany_user

我怎麼能在軌道4,5解決這個問題?

+0

我猜你錯誤地複製了你的語法的問題?它應該讀爲'belongs_to:account, - > {where(company_account:self.company_user)}',對不對? –

+0

感謝Chris Peters的回答,我複製了http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference#4.1.3「範圍for belongs_to」的語法;我會嘗試你的答案。 –

+0

相同的錯誤「未定義的方法'company_user'」 –

回答

0

試着這麼做:

belongs_to :account, -> { where("company_account_id = ?", self.send(:company_user).id) } 
+0

Bratsche,我試過你的例子,這讓我「SyntaxError ...」 –

+0

對不起。我做了一些編輯,看看這是否有幫助。 – bratsche

0

我解決我的問題,通過使用我的帳戶模型組成的主鍵。

爲此,我用this gem