繁体   English   中英

Rails has_one:通过赋值触发“未定义的方法`update_attributes'”错误

[英]Rails has_one :through assignments trigger a “undefined method `update_attributes'” error

我无法弄清楚为什么rails has_one:通过关联不接受任务。 这是错误:

>> 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单元测试。

您可能需要has_one:primary_membership,然后使用该帐户。

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

那么你也能,

user.primary_membership.account

尝试将相关联关系设置为belongs_to而不是has_one

我觉得我之前遇到过这种情况并且认为这样做了。 不幸的是,我没有进一步研究为什么has_one :through是否有意义。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM