Validating two models

Hi,

I have a model Account wich “has_one” model called UserData. Both models
use validation.

Model contains user name, email etc.

class Account < ActiveRecord::Base
has_one :user_data, :foreign_key => “user_id”

validates_presence_of :email
end

Model contains firstname, lastname etc.

class UserData < ActiveRecord::Base
set_table_name(“user_data”)

validates_length_of :firstname, :lastname, :maximum => 10
end

I save the model in the AccountController like that:

@account = Account.new(params[:account])
@account.user_data = UserData.new(params[:user_data])
@user_data = @account.user_data
@account.save

Now I got the validation errors for Account, but not for UserData. How
can I get these errors for both models?

Thanks
Steffen

On 7/29/06, Steffen B. [email protected] wrote:

validates_presence_of :email
I save the model in the AccountController like that:
Steffen


Posted via http://www.ruby-forum.com/.


Rails mailing list
[email protected]
http://lists.rubyonrails.org/mailman/listinfo/rails

In your view include a call to error_messages_for for both objects

<%= error_messages_for ‘account’ %>
<%= error_messages_for ‘user_data’ %>

The error messages for will look up an instance variable with the name
provided, query the AR object for it’s errors and display them. You can
list as many as you like.

I tried this already. But it only works if I explicitly save
“user_data”. But user_data is implicitely saved by “@account.save
because it is in an “account has_one user_data” relationship.

When saving explicitly I have the problem that account may be saved but
user_data is not because of validation errors. Maybe I need a
transaction here? What would be the syntax?

On 31 Jul 2006 07:56:10 -0000, Steffen B.
[email protected] wrote:

I tried this already. But it only works if I explicitly save
“user_data”. But user_data is implicitely saved by “@account.save
because it is in an “account has_one user_data” relationship.

When saving explicitly I have the problem that account may be saved but
user_data is not because of validation errors. Maybe I need a
transaction here? What would be the syntax?

user_data.valid? could help you out on the validation, but you
definitely want a transaction here, unless you want to allow accounts
without user_data. I like to enforce this referential integrity at
the DB as well.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs