开发者

Why can't ActiveRecord assign object to association attribute?

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

开发者_如何学JAVAclass 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.


Try using nested_attributes.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜