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.
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…
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?
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.