Validate associations

Hello,

I have a simple Review model (article has many reviews):

class Review < ActiveRecord::Base
belongs_to :article

validates_presence_of :article_id

validates_associated :article
end

However, if I set the article_id to some random article id that doesnt
exist, it wont show an error and will save the record to the database as
it would normally do.

How do you do validate associations?

Hello Al, thank you for pointing this out.
You are right, it seems to be intuitive that validates_associated should
check the existence of the associated object. But it doesn’t.
Actually the problem is well known…

http://forums.pragprog.com/forums/74/topics/732
http://dev.rubyonrails.org/ticket/5369
http://blog.hasmanythrough.com/2007/7/14/validate-your-existence

…but running Rails 2.3.4 the misunderstanding does not appear to be
addressed.

So, for example, following the hints you can see in the pages linked
above, your models could be:

review.rb

class Review < ActiveRecord::Base
belongs_to :article
validates_presence_of :article_id
validates_associated :article
validate :existence_of_article, :if => :article_id?

def article_id? # just not to bury the users with pointless error
messages
return true if article_id and !article_id.blank?
end

def existence_of_article # this actually checks the existence of the
object, called by validate
errors.add(:article_id, “must exist to save the review.”)
unless article_id? and article
end
end

#article.rb
class Article < ActiveRecord::Base
has_many :reviews # not involved in validation of the review, as far I
can understand
end

You could use the plugin, but I always do as shown above, because I
prefer to have the least of dependencies on external components, and see
what’s going on.

Hope this helps.

Luca B.

Al F. wrote:

Hello,

I have a simple Review model (article has many reviews):

class Review < ActiveRecord::Base
belongs_to :article

validates_presence_of :article_id

validates_associated :article
end

However, if I set the article_id to some random article id that doesnt
exist, it wont show an error and will save the record to the database as
it would normally do.

How do you do validate associations?