引入多态关联后下降保存

时间:2013-10-16 10:29:34

标签: ruby-on-rails

在我引入多态关联后,我在Railsapp中遇到了问题。该应用程序由可以具有多个属性的团队(以及其他模型)组成。所以我跟着railscasts插曲并想出了这个:

应用程序/模型/ attribute.rb

class Attribute < ActiveRecord::Base
  attr_accessible :content

  belongs_to :attributable, polymorphic: true
end

应用程序/模型/ team.rb

class Team < ActiveRecord::Base
  has_many :attributes, as: :attributable
  accepts_nested_attributes_for :attributes
end

这样做之后我在IRB会话中遇到了这个:

irb(main):001:0> t = Team.new(name: "Test")
=> #<Team id: nil, name: "Test", created_at: nil, updated_at: nil, scopes_mask: nil>
irb(main):002:0> t.save
   (0.3ms)  begin transaction
            commit transaction
=> true
irb(main):003:0> t.save
   (0.4ms)  begin transaction
            rollback transaction
NoMethodError:   Attribute Load (0.6ms)  SELECT "attributes".* FROM "attributes" WHERE "attributes"."attributable_id" = 1 AND "attributes"."attributable_type" = 'Team'
undefined method `keys' for []:ActiveRecord::Relation

因此错误恰好发生在以前记录的记录上。第一次保存的构建记录和属性完全正常,加载记录也是如此。

我希望对此情况有任何帮助。 此致

1 个答案:

答案 0 :(得分:1)

attributes是已经是ActiveRecord一部分的方法。我强烈怀疑命名您的关联attributes也会导致问题。如果您使用不同的名称来避免与ActiveRecord内部冲突,它应该可以正常工作。