开发者

Polymorphic model question in rails - does it maintain the relationship for you?

开发者 https://www.devze.com 2023-03-04 01:47 出处:网络
Let\'s say you have a SiteUpdate and a Comment model, and you want to make Comment polymorphic. You make comment hold a \"commentable_id\" and \"commentable_type\"...

Let's say you have a SiteUpdate and a Comment model, and you want to make Comment polymorphic. You make comment hold a "commentable_id" and "commentable_type"...

Here's our comment model:

class Comment < ActiveRecord::Base

  belongs_to :commentable, :polymorphic => true

  validates_presence_of :content
  validates_presence_of :commentab开发者_运维问答le

end

Here is our SiteUpdate:

class SiteUpdate < ActiveRecord::Base

  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  has_many :comments, :as => :commentable

  validates_presence_of :subject
  validates_length_of :subject, :maximum => 80
  validates_presence_of :intro
  validates_length_of :intro, :maximum => 200
  validates_presence_of :text
  validates_presence_of :author

  scope :sorted, order("site_updates.created_at desc")

end

Does Rails link the commentable to the site_update instance, or do I have to do that manually?

  @site_update.comments << Factory.build(:comment, :commentable_id => nil)
  @site_update.save

This fails -> it complains that the comment.commentable_id should not be blank (I set this validation in the Comment model).

So do I do this manually, or do I set this up incorrectly?

Or do I just not validate it at all?


I'm making an assumption that your @site_update object is a new object. If so...

There's a somewhat annoying thing about rails associations. You can't really add them before the record is saved.

What's happening is, you have a new site update object without an ID. You build a new comment object for that site update, so it sets the commentable_type to "SiteUpdate", however, there's no ID yet, so it sets the commentable_id to nil. You save, and it bubbles out to save associated objects, but it doesn't set the comment commentable_id to the SiteUpdate ID, because it doesn't exist.

So if you change it around to be :

@site_update.save
@site_update.comments << Factory.build(:comment, :commentable_id => nil)
@site_update.comments.map { |c| c.save }

it should work.

If it's not a new record...it should work as is.

0

精彩评论

暂无评论...
验证码 换一张
取 消