views:

480

answers:

2

I can't figure out why rails has_one :through associations don't accept assignments. Here is the error:

>> 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
>>

Given:

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

It seems like these assignments should work unless I'm missing something. They appear to work in the Rails unit tests.

A: 

Try setting up the association in question as belongs_to instead of has_one.

I feel like I've run into this before and think that did the trick. Unfortunately, I didn't look into much further to determine why has_one :through does or does not make sense.

technicalpickles
That won't work because this is habtm type relationship.
Brad Gessler
+2  A: 

You probably want a has_one :primary_membership, and then use the account through that.

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

Then you can,

user.primary_membership.account
Joshbuddy
That works! In retrospect, it makes sense that AR works this way. The details were a bit foggy in the documentation.
Brad Gessler