On Viernes, 7 de Mayo de 2010 01:03:38 Iñaki Baz Castillo escribió:
> Hi, I'm not sure if the following is a common issue in ActiveRecords
> or in ActiveScaffold and how it manages models in subforms:
>
> - Client has_many Routes (through "client_id" in "routes" table as usual).
>
> - In Client model I need this validation:
>     validates_presence_of :client_id, :if => Proc.new { |route|
> route.enabled }

Validations should be added to association:
validates_presence_of :client, :if => Proc.new { |route| route.enabled }

>
> - I need such validation because it's also possible to directly create
> Routes in a separate way (without the need of creating a Client and a
> Route(s) belonging ot it). In such case I need to ensure that the
> route entry belongs to a Client just if the "enabled" field is checked
> (in the Clientcontroller subform for Route such checkbox is hidden).
>
> - If I want to create a Client with a Route (by filling the subform)
> then I get this error:
>     "client_id cannot be empty"
>

You get that error because client is not saved when validations are checked, 
so it has no id and client_id is still nil. If you set the validation in 
client association, it will work.

> I think this error occurs because AS creates first the Route model
> (just in memory, not yet in DB) for which, of course, there is not yet
> a client_value, am I right? what is the workaround for this?

There is a client in route, but there is no client_id. The actual code is 
like:
@record = Client.new [some params]
@record.routes.build [some params]
@record.save if @record.valid? && @record.routes.all?(&:valid?)

Associations are set when valid? is called, but primary keys aren't set 
because records are not saved yet.

>
> PS: If this is a pure ActiveRecord related question please just tell
> it to me so I'll investigate in Rails/ActiveRecords forums.

Really is an ActiveRecord related question, because the usual way to save a 
record with associations from a form is build all records, check validations 
and after that save them. So you should add validations in associations 
instead of foreign keys.

Also, I wouldn't add a validation for client present if a route can exist 
without client. When you are filling a client form with routes subforms you 
ensure in the controller client is set, so I would remove that validation and 
hidden field


-- 
Sergio Cambra .:: entreCables S.L. ::.
Mariana Pineda 23, 50.018 Zaragoza
T) 902 021 404 F) 976 52 98 07 E) [email protected]

-- 
You received this message because you are subscribed to the Google Groups 
"ActiveScaffold : Ruby on Rails plugin" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/activescaffold?hl=en.

Reply via email to