validates_associated

Hello all,

Having a bit of a problem with validates_associated. I assume I’m missing something out but basically got these two models -

class Seller < User

has_one :profile, :foreign_key => ‘user_id’, :dependent => :destroy

has_many :properties

validates_associated :profile

end

class Profile < ActiveRecord::Base

belongs_to :user

validates_presence_of :title, :forename, :surname, :address_a

end

My form looks like

Register as seller

<%= error_messages_for :user %>

<% form_for :user do |f| -%>

<label for="login">Login</label><br />

<%= f.text_field :login %>

<label for="email">Email</label><br />

<%= f.text_field :email %>

<label for="password">Password</label><br />

<%= f.password_field :password %>

<label for="password_confirmation">Confirm Password</label><br/>

<%= f.password_field :password_confirmation %>

<% fields_for :profile do |p| %>

<label for="profile_title">Title</label><br />

<select id="profile_title" name="profile[title]">

	<option value="Mrs">Mrs</option>

	<option value="Mr">Mr</option>

	<option value="Miss">Miss</option>

	<option value="Ms">Ms</option>

	<option value="Dr">Dr</option>

</select>

<label for="profile_forename">Forename</label><br />

<%= p.text_field :forename %>

<label for="profile_surname">Surname</label><br />

<%= p.text_field :surname %>

<label for="profile_address_a">Address</label><br />

<%= p.text_field :address_a %>

<label for="profile_address_b">Address</label><br />

<%= p.text_field :address_b %>

<label for="profile_town">Town/City</label><br />

<%= p.text_field :town %>

<label for="profile_county">County</label><br />

<select id="profile_county" name="profile[county]">

<%= county_options_for_select %>

</select>

<label for="profile_postcode">Postcode</label><br />

<%= p.text_field :postcode %>

<label for="profile_mailing_list">Subscribe to mailing list</label><br />

<%= p.check_box :mailing_list  %>

<% end %>

<%= submit_tag 'Sign up' %>

<% end -%>

Basically when I submit the form with the missing fields required by the Profile model, the form submits anyway.

Any suggestions?

Thanks in advance,

Alastair

You also want validates_presence_of :profile

jeremy

Hi Jeremy,

That seems to result in “Profile can’t be blank” whether all the fields are filled or not. Any ideas?

Thanks!

Alastair

Assign the profile to the user before validating the user.

Best, jeremy

Thanks again, missed that bit! It was late. All working now.

Cheers,

Alastair

Alastair, could you post your fixed code? I'm not sure I follow what you changed to make it work.

Thanks, Ben

Hi Ben,

It wasn’t my models that were incorrect, I had missed some code in the controller that linked the user with it’s user profile.

Basically this: @profile = @user.profile = Profile.new(params[:profile]) fixed the problem. It wasn’t the validates, it was that the user and it’s profile were unrelated.

Cheers,

Alastair