当我有一个继承的类时,我在执行反向多态关联时遇到了麻烦。有谁知道发生了什么事?
ruby-1.9.2-rc2 > Label.first
=> #<Label id: 1, owner_id: 1, owner_type: "Student", name: "Lorem", created_at: "2011-01-23 05:02:29", updated_at: "2011-01-23 05:02:29">
ruby-1.9.2-rc2 > Label.first.owner
=> #<Student id: 1, email: "alice1@example.com", ..., avatar_updated_at: nil>
ruby-1.9.2-rc2 > Label.first.owner.labels
=> []
class Student < User
has_many :labels, :as => :owner
class Label < ActiveRecord::Base
belongs_to :owner, :polymorphic => true
注意:只是为了好的措施(不是这应该是不同的,但以防万一......)
User.find(1).labels
=> []
另外
l = Label.find(4)
=> #<Label id: 4, owner_id: 2, owner_type: "Student", name: "sit", created_at: "2011-01-23 05:02:29", updated_at: "2011-01-23 05:02:29">
ruby-1.9.2-rc2 > l.owner_type = "User"
=> "User"
ruby-1.9.2-rc2 > l.save
=> true
ruby-1.9.2-rc2 > Student.find(2).labels
=> [#<Label id: 4, owner_id: 2, owner_type: "User", name: "sit", created_at: "2011-01-23 05:02:29", updated_at: "2011-01-23 07:13:37">]
答案 0 :(得分:0)
仍然不确定为什么会失败(好吧,我可以猜测,考虑到学生/用户的二分法),但为了将来的参考,这个黑客有效:
has_many :labels, :conditions => ["owner_type = ?", "Student"],
:foreign_key => "owner_id"