Rajanand02
Rajanand02

Reputation: 1303

validates_associated to validate the association between two models

I have two models Post model and Comment model..First if a create a post it will have a post id of 1 then while creating a comment i can give association to the post using post_id equal to 1 but if i create a comment with post id of 2 which does not exist it would still go ahead and create a comment but with id of 'nil'..I want to ensure that the comment will be created only if the respective post_id is present.

class Post < ActiveRecord::Base
 has_many :comments, dependent: destroy
end

class Comment < ActiveRecord::Base
  belongs_to :post
  validates_associated: post
end

As per my understanding validates_associated checks whether the validations in post model passes before creating a comment. Clarify me if i am wrong and what would be a appropriate solution for the above scenario?

Upvotes: 2

Views: 374

Answers (2)

kiddorails
kiddorails

Reputation: 13014

First, the preferred way of setting the association b/w Post-Comment here is by :

def new
  @product = Product.first
  @comment = @product.comments.build
end

def create
  @product = Product.find(params[:comment][:post_id])
  @comment = @product.comments.create(comment_params)
end

For your particular scenario, I'm assuming that post_id is coming in params via some form or something, and then you wish to create a comment only if the post with that particular post_id exists. This can be done by adding following in Comment model:

validates :post, presence: true, allow_blank: false

OR

validate :post_presence, on: :create
def post_presence
  errors.add(:post_id, "Post doesn't exist") unless Post.find(post_id).present?
end

You can even do the same thing at controller-side with before_action/before_filter hooks.

Upvotes: 1

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

You can do this to validate the presence of post_id

class Comment < ActiveRecord::Base
  belongs_to :post
  validates :post_id, :presence => true
end

or to validate association, you can use

class Comment < ActiveRecord::Base
  belongs_to :post
  validates_presence_of :post
end

Upvotes: 0

Related Questions