user2911232
user2911232

Reputation:

Validation in Polymorphic association with validates_associated

I have these models: Post, TextPost and PhotoPost and I use polymorphic association.

You can find these three models here or look below.

post.rb

class Post < ActiveRecord::Base
  belongs_to :user
  default_scope { order ("created_at DESC")}
  belongs_to :content, polymorphic: true
  has_reputation :votes, source: :user, aggregated_by: :sum
end

photo_post.rb

class PhotoPost < ActiveRecord::Base
  has_attached_file :image, styles: {
    post: "200x200>"
  }
end

text_post.rb

class TextPost < ActiveRecord::Base
  attr_accessible :body
end

What I want, is to validate the presence of :body and :image when a users submits a text_post or photo_post respectively. So far, I found out that I have to use validates_associated. The full project can be found on Github.

I have experiment a lot to find out how validates_associated works and searched for examples online but I don't have a clue what's going on.

(If you need any more info please let me know) Any help/guidance is greatly appreciated.

Upvotes: 3

Views: 2138

Answers (1)

Deej
Deej

Reputation: 5352

I think for starters there needs to be some form of association between these 3 models here. You have Post, PhotoPost and TextPost. As a post can has a type of post. Also remember that type in rails is a reserved word. But anyways your models should be set out as followed:

class Post< ActiveRecord::Base
  belongs_to :postable, polymorphic: true
end

class PhotoPost < ActiveRecord::Base
  has_many :posts, as: :postable
end

class TextPost < ActiveRecord::Base
  has_many :posts, as: :postable
end

As from looking at the snippet you provided it doesn't show any set up of polymorphic association. With regards to validating the association of the polymorphic association you might want to take a read of this answer: Validate presence of polymorphic parent. Furthermore also might want to read this article: Validating a polymorphic association for a new record . The purpose of the validate_associated validation helper simply ensures that the association between the two records are valid or as they put it works. In your case if you were to use that validation helper. This would not be what you'd want because all that would be doing is validating the association between the two models. See the second link I provided this is what I believe you are after.

Also in your controller you need to build the relationship between the models. So in your controller I think you could have something like this inside your new action:

  def new
    @Post = Postfind(params[:id])
    @PhotoPost = @post.photoposts.build
    @TextPost = @post.textposts.build
  end

Upvotes: 1

Related Questions