Railsがhas_one:throughアソシエーションが割り当てを受け入れない理由を理解できません。エラーは次のとおりです。
>> 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の単体テストでは機能しているようです。
回答:
回答№1は4has_one:primary_membershipが必要な場合があり、それを介してアカウントを使用します。
has_one :primary_membership, :class_name => "Membership", :conditions => {:role => 1}
その後、できます、
user.primary_membership.account
回答№2の場合は0
問題の関連付けを次のように設定してみてください belongs_to
の代わりに has_one
.
私はこれまでにこれに遭遇し、それがトリックをしたと考えているように感じます。残念なことに、私は理由を決定するためにこれ以上詳しく調べませんでした has_one :through
意味がありますか。