Rails 3 belongs to validation

23 views
Skip to first unread message

GeorgeFromTheBank

unread,
Oct 8, 2014, 9:20:25 AM10/8/14
to rubyonra...@googlegroups.com
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
end

I'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
end

However 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

Jason Fleetwood-Boldt

unread,
Oct 8, 2014, 9:37:49 AM10/8/14
to rubyonra...@googlegroups.com

validates :user, presence: true,  uniqueness:  true

Much easier than what you are trying to do.

Note that this will work in 99.999% of the time, 0.001% of the time you will get duplicate records in your database because of race conditions

Alternatively, if your user really is going to have only 1 address, then why isn't the address_id field inside of the User model? (You would then have your User belong_to :address). Seems like a more appropriate model for what you are trying to do. 


-Jason



--
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-ta...@googlegroups.com.
To post to this group, send email to rubyonra...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/rubyonrails-talk/f9593b29-3a3a-44e2-976c-3016c9d4fbea%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

----

Jason Fleetwood-Boldt

All material © Jason Fleetwood-Boldt 2014. Public conversations may be turned into blog posts (original poster information will be made anonymous). Email ja...@datatravels.com with questions/concerns about this.

GeorgeFromTheBank

unread,
Oct 8, 2014, 11:01:18 AM10/8/14
to rubyonra...@googlegroups.com
Thanks for the reply Jason (I almost wrote Json :), I really appreciate it.

Pratap Patil

unread,
Oct 20, 2014, 9:01:47 AM10/20/14
to rubyonra...@googlegroups.com

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
Reply all
Reply to author
Forward
0 new messages