【问题标题】:Why can't ActiveRecord assign object to association attribute?为什么 ActiveRecord 不能将对象分配给关联属性?
【发布时间】:2010-09-26 02:24:57
【问题描述】:

我花了半个工作日试图在 AR 中追踪这一点。给定一个模型设置,如:

class Publication < ActiveRecord::Base
  has_many :subscriptions
end

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

在控制器中,

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

在服务器启动后第一次调用它时,它在开发模式下完美运行。然而,第二次,它从

引发错误
~/.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

设置

config.cache_classes = true

config/environments/development.cfg 中使问题消失。

AR 在哪里处理为belongs_to 关联创建attr_accessor/writer,为什么这会在第一次而不是第二次调用时起作用?似乎在请求之间卸载和重新加载类时没有定义访问器?更多信息:PublicationSubscription 正在使用 STI,如果这不应该有任何区别,则在基类上定义关联。这是 ruby​​ 1.9.1 和 Rails/AR 2.3.8

感谢任何线索。

【问题讨论】:

  • 是拼写错误吗? has_manybelongs_to 不是符号...应该是 has_many :subscriptions...
  • 是的,抱歉,错字已更正。问题不是由于拼写错误 - 第一个请求之后的行为不同。就好像关联访问器 user= 第二次未定义或未重新定义。我害怕做出解决方法(例如分配 id),因为语法渗透到应用程序中。它应该可以工作。

标签: ruby-on-rails activerecord associations


【解决方案1】:

尝试使用nested_attributes

【讨论】:

  • 不。不尝试设置用户的属性,只是尝试与现有的用户对象关联。即 create(user_id: @current_user.id) 但使用对象语法,与分配 has_one/blongs_to 关联相同。您是说无论嵌套属性如何,语法都是无效的?
【解决方案2】:

啊,“第一次在开发模式下工作”但在随后的页面重新加载时不起作用。可能与 Lighthouse #1339 有关:https://rails.lighthouseapp.com/projects/8994/tickets/1339-arbase-should-not-be-nuking-its-children-just-because-it-lost-interest 运行 cache_classes = true “修复”它,或者这个补丁在开发模式下运行。

【讨论】:

    猜你喜欢
    • 2014-04-05
    • 2018-02-02
    • 1970-01-01
    • 1970-01-01
    • 2015-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 2011-09-22
    相关资源
    最近更新 更多