引入多态关联后,我在 Railsapp 中遇到了问题。该应用程序由可以具有多个属性的团队(以及其他模型)组成。所以我跟着 railscasts 的那一集想出了这个:
应用程序/模型/属性.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
所以错误只发生在以前记录的记录上。在第一次保存之前建立记录和属性非常好,加载记录也是如此。
我希望对这种情况有任何帮助。真挚地