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

Community
  • 1
  • 1
GavinBelson
  • 2,514
  • 25
  • 36
  • 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. – max Apr 05 '17 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? – GavinBelson Apr 05 '17 at 21:43

0 Answers0