class Followup < ActiveRecord::Base
belongs_to :post
belongs_to :comment
end
这个模型只需要一个post或一个comment,但只需要其中的一个。
以下是我要做的事情的rspec:
it "should be impossible to have both a comment and a post" do
followup = Followup.make
followup.comment = Comment.make
followup.should be_valid
followup.post = Post.make
followup.should_not be_valid
end
我可以看到一系列的解决方案,但最优雅的方法是什么呢?
最佳答案
我认为你真正想要的是多态性关联。
Ryan在Railscast #154中解释得很好。
class Followup < ActiveRecord::Base
belongs_to :followupable, :polymorphic => true
end
class Post < ActiveRecord::Base
has_many :followups, :as => :followupable
end
class Comment < ActiveRecord::Base
has_many :followups, :as => :followupable
end