ruby on rails - How to handle validations between associated objects? -


i having difficulty in validating 2 objects across complex associations. here's example of have:

car.rb

class car   has_many :passengers end 

passenger.rb

class passenger   belongs_to :car   belongs_to :info end 

validations need do:

  • the number of passengers limited
  • passengers have association object called info has "employer" string. passengers must have same employer.

the interface has multiselect box choose passengers. once you're done selecting passengers, click "create" (or "update", has it's own set of problems).

when controller tries create car, needs run car validations, passenger validations need pass (employer check), , car needs ensure it's not exceeding passenger count. if 1 of these fails, need reset , take them new page.

during update, if fails, need restore original passengers car. i'm not sure how perform validations without saving objects database though. in addition, once objects saved database, if validations fail, don't know how restore previous passengers.

how can validate associated objects before saving them database?

you can use custom validation custom_validations

 validate :validate_passengers    def validate_passengers     errors.add(:passengers, "too much") if tags.size > 5 #your limit   end 

this validate limit of passengers car


Comments

Popular posts from this blog

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.Error occurred in starting fork -

windows - Debug iNetMgr.exe unhandle exception System.Management.Automation.CmdletInvocationException -

configurationsection - activeMq-5.13.3 setup configurations for wildfly 10.0.0 -