1

I have a model User and a nested model Mobility

class User < ActiveRecord::Base
   has_many :mobilities, :dependent => :destroy
   accepts_nested_attributes_for :mobilities
end

and

class Mobility < ActiveRecord::Base
  belongs_to :mobile_user, :class_name =>  'User'
  validates :city_id, :presence =>true
  validates :user_id, :presence =>true
  validates :city_id, :uniqueness => {:scope => [:user_id]}
end

my view

=form_for @user, :as => :user, :html =>{ :class => 'form-horizontal'} do |f|
  =f.fields_for :mobilities  do |city_form|
    =city_form.text_field :city_id, :id => "city_id_#{index}"
    = f.submit "Retour"

my problem is that when I submit the form Rails render me this validation error:

Mobilities user > doit être rempli(e)

But if a I comment this line:

#validates :user_id, :presence =>true

Both, my Mobility and User objects get saved and know what: user_id field of @mobility is OK (indicatie my @user's ID)

If I send the form with 2 identical mobility inside, both model get saved but it seems my validation of uniqueness didn't check nothing because i have 2 Mobility object with same user_id and city_id in my database...

In fact it seems like my validation can't read my user_id 's key when validating. I understand that because my User model did'nt get saved yet and doesnt have any ID yet... but that is my question:

How can i check both: presence of user_id and uniqueness with scope ???

alex
  • 357
  • 3
  • 14
  • I think i get my answer here: http://stackoverflow.com/questions/2772236/validates-uniqueness-of-in-nested-model-rails and here: http://stackoverflow.com/questions/4011846/accepts-nested-attributes-for-validation – alex Jun 12 '12 at 21:11

0 Answers0