Validating a form by verifying two attributes in a related t

I have a table called Contracts that includes the Name and Contact
Information for all my Independent Contractors. Each Independent
Contractor (IC) will have many [work] Schedules. The IC has to submit
a schedule every week, but I do not want to setup a complicated
authentication system that is hard to maintain. So, I’d like to have
a simple form where the ICs must pick their name from a list and
manually type in their own ZIP code to let the program know it is
actually them submitting the form.

My question is how can I validate the form by checking that the ZIP
code matches the name picked (which both reside in my contracts table)
before allowing the IC to create the schedule? I would imagine I would
have to create a custom ‘validate’ method in my Schedules model, but
I’m not sure how to begin.

Cheers,
Brad

Hi

I guess you have a model that looks like this

class Schedule < ActiveRecord::Base

belongs_to :contract

end

First, you seem to need to add

attr_accessor :contractor_zip

so that you’ll be able to put a field to enter the zip code in the form.

Then you can write your custom validation method:

def validate
errors.add(:contractor_zip, ‘is invalid’) unless contract.zip ==
contractor_zip
end

I didn’t test this code, but it should check whether the zip of the
associated contract is equal to the zip entered in the form. I also
assume that the drop down with contractor names will populate the
contract_id field of the Schedule model.

Hope that helps
Eugene

Hi Eugene,

Sorry, I could have offered more information. My tables are actually
a bit more complicated than I led on, so I had to modify the validate
method a little bit.

I have 3 tables:
*Applicants (has_one :contract)
*Contracts (belongs_to :applicant)
*Schedules (belongs_to :contract)

Applicants table actually contains the ZIP code (Before they are
contracted, the apply and contact information is stored in the
applicants table).

I had to modify the validate method to be able to link through the
contracts table to my applicants table. It seems to be working
though!

attr_accessor :contract_zip

def validate
errors.add(:contract_zip, ‘is invalid’) unless
contract.applicant.zip == contract_zip
end

I never really understood attr_accessor until now. Thanks SO much for
your help!

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs