Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Validating Associated models in rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 462
    Comment on it

    Hi Friends,
    I am here again with one more topic in rails that is validates_associated. So as we all know that associations are a major part in every kind of Relation Databases. So what happens if we have one model with some associated objects with it and if we save our object its associated objects also gets saved. So it is needed to validate the object as well as its associated objects before saving.
    In rails above requirement is achieved by validates_associated. It validates each associated objects of the Object before saving that object.

    Suppose we have a class Findnerd that has associated blogs with it and it belongs to a Company. So our class will look like after adding validates_associated as:

    class Findnerd < ActiveRecord::Base
      has_many :blogs
      belongs_to :company
    
      validates_associated :blogs, :company
    end
    

    So this is how validates_associated is used . One thing to be noted is that it must not be used on each side of association otherwise it will get into infinite loop.
    The default error message for validates_associated is "is invalid".

    Hope you liked this and it proved helpful for you.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: