Sunday, 15 January 2012

Limiting model validation to only records associated with the current_user in Rails 3.2 -



Limiting model validation to only records associated with the current_user in Rails 3.2 -

i have invitations scheme allows users nominate others bring together beta. need validate email address user sending invitation , ensure email address unique, within scope of current_user's list of invitations.

in other words, model should allow same email address exist within invitation system, not allow duplicates within scope of current_user's list of invites.

my usermodel has:

has_many :invitations validates_uniqueness_of :email

and invitationmodel has:

belongs_to :user

i can't set validates_uniqueness_of :email within invitationmodel since need allow multiple instances of given email address within database, ensure each instance has unique sender (user).

any ideas on how limit validation scope of current_user?

it sounds need scope on validation. allow same email address used multiple times, 1 time per user.

validates_uniqueness_of :email, scope: :user_id

also, since email addresses case-insensitive, recommend adding insensitivity scope.

validates_uniqueness_of :email, scope: :user_id, case_sensitive: false

cite: http://apidock.com/rails/activerecord/validations/classmethods/validates_uniqueness_of

ruby-on-rails-3 validation rails-activerecord

No comments:

Post a Comment