views:

52

answers:

2

I've spent half a working day trying to track this down in AR. Given a model setup like:

class Publication < ActiveRecord::Base
  has_many :subscriptions
end

class Subscription < ActiveRecord::Base
  belongs_to :publication
  belongs_to :user
end

In controller,

  @new_subscription = publication.subscriptions.create( user: @current_user ) { |r| ... }

Works perfectly in development mode first time it is invoked after a server start. Second time however, it throws an error from

~/.rvm/gems/ruby-1.9.1-p378/gems/activerecord-2.3.8/lib/active_record/base.rb:2906:in `block in assign_attributes':
ActiveRecord::UnknownAttributeError: unknown attribute: user

Setting

config.cache_classes = true

in config/environments/development.cfg makes the problem disappear.

Where does AR handle creating the attr_accessor/writer for a belongs_to association, and why would this work the first but not the second time invoked? Seems like the accessor is not getting defined when the class is unloaded and reloaded between requests? Further information: the Publication and the Subscription are using STI, and the associations are defined on the base classes if that shouldn't make any difference. This is ruby 1.9.1 and Rails/AR 2.3.8

Grateful for any clues.

+1  A: 

Try using nested_attributes.

Bitterzoet
nope. not trying to set the attributes of user, just trying to associate with the existing user object. i.e. create(user_id: @current_user.id) but with the object syntax, same as assigning the has_one/blongs_to association. are you saying the syntax is invalid regardless of nested attributes?
tribalvibes
A: 

Ah, "works the first time in dev mode" but not on subsequent page reloads. Probably related to Lighthouse #1339: https://rails.lighthouseapp.com/projects/8994/tickets/1339-arbase-should-not-be-nuking-its-children-just-because-it-lost-interest Running with cache_classes = true "fixes" it, or this patch in dev mode.

tribalvibes