0

I have a validation that needs to apply only per a certain project that a user is in. The solution I came up with is to call this model method from the controller:

controller:

Client.validate_uniq_record(params[:project_id])

model:

def self.validate_uniq_record(proj_id)
    validates_uniqueness_of :item, scope: :price, conditions: -> {where(project_id: proj_id)}
end

From reading other questions, it looks like passing a param to a model is a big nono: How to access params in the callback of a Rails model? I could not figure out how to do this through a virtual attribute either.

How would I validates_uniqueness_of for only the current project the user is in?

Note, the Client object has a project_id column as an FK

2
  • 1
    You would usually use an association and use validates with the scope option pointing to the foreign key in conjunction with a compound index in the DB. Commented Apr 5, 2017 at 21:30
  • yep! just setting the scope to project_id and calling the validation in the model without a method worked perfectly. Do you want to post this as an answer and I'll accept? Commented Apr 5, 2017 at 21:43

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.