2009-12-03 52 views
1

我不明白爲什麼rails has_one:通過關聯不接受任務。以下是錯誤:Rails has_one:通過賦值觸發一個「未定義的方法`update_attributes'」錯誤

>> u = User.new 
=> #<User id: nil, created_at: nil, updated_at: nil> 
>> u.primary_account 
=> nil 
>> u.primary_account = Account.new 
NoMethodError: undefined method `update_attributes' for #<Class:0x1035ce5f0> 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:1959:in `method_missing' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:380:in `send' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:380:in `method_missing' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/base.rb:2143:in `with_scope' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_proxy.rb:206:in `send' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_proxy.rb:206:in `with_scope' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/association_collection.rb:376:in `method_missing' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations/has_one_through_association.rb:11:in `create_through_record' 
    from /Library/Ruby/Gems/1.8/gems/activerecord-2.3.5/lib/active_record/associations.rb:1274:in `primary_account=' 
    from (irb):9 
>> 

考慮:

class User < ActiveRecord::Base 
    has_many :memberships 
    has_many :accounts, :through => :memberships 
    has_one :primary_account, :through => :memberships, :source => :account, :conditions => { :role => 1 } # assume memberships.role of type integer in the db 
end 

class Membership < ActiveRecord::Base 
    belongs_to :account 
    belongs_to :user 
end 

class Account < ActiveRecord::Base 
    has_many :memberships 
    has_many :users, :through => :memberships 
end 

好像這些任務應該工作,除非我失去了一些東西。他們似乎在Rails單元測試中工作。

回答

4

您可能想要一個has_one:primary_membership,然後通過該帳戶使用該帳戶。

has_one :primary_membership, :class_name => 'Membership', :conditions => {:role => 1} 

然後你可以,

user.primary_membership.account 
+0

工作!回想起來,AR以這種方式工作是有道理的。文檔中的細節有點模糊。 – 2009-12-03 05:39:41

0

嘗試將有問題的關聯設置爲belongs_to而不是has_one

我覺得我之前遇到過這種情況,並認爲這樣做。不幸的是,我沒有仔細研究,以確定爲什麼has_one :through確實或沒有意義。

+0

這是行不通的,因爲這是的habtm類型的關係。 – 2009-12-03 05:33:05

相關問題