Ruby on Rails
Monday, October 20, 2014
validates :user, uniqueness: true
is simple way(When you specify association then it also check other model validation) also other way is add custom validation for check uniquness
is simple way(When you specify association then it also check other model validation) also other way is add custom validation for check uniquness
On Wednesday, October 8, 2014 6:50:25 PM UTC+5:30, GeorgeFromTheBank wrote:
Hello,I want to restrict my users having more than one address.Here are the definitions from my classes :class User < ActiveRecord::Base has_one :address, dependent: :destroy end class Address < ActiveRecord::Base belongs_to :user validates :user, presence: true validate :user_association def user_association unless Address.where(user_id: user.id).count == 0 errors.add(:user_id, 'Only one address per user') end end endI'm creating my address from user model, like this :def create_address_relation a = Address.create(address_type: @type.to_s, user_id: id) self.address = a endHowever when I'm able to create two address objects for same user. (I'm using paranoia gem for soft deleting objects, not sure if that is relevant)Any suggestion how to make validations work? except unique index on the db
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to rubyonrails-talk+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/49cb943d-0557-4e35-8704-c9245ff7fe43%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment