Forms and Relationships

Hey,

Alright so I have a User model that has roles and can access them
through like User.role.____ and that works fine… the question is how do
I set that up when making a form… like I have

<%= text_field ‘role’, ‘title’, :value => “#{@user.role.title}” %>

is there a way to automatically associate the field with the value
without specifying the value myself like that?

On Jun 19, 2006, at 04:34 PM, Ray M. wrote:

Alright so I have a User model that has roles and can access them
through like User.role.____ and that works fine… the question is
how do
I set that up when making a form… like I have

<%= text_field ‘role’, ‘title’, :value => “#{@user.role.title}” %>

is there a way to automatically associate the field with the value
without specifying the value myself like that?

In actuality, Rails is trying to find that field’s value to put in
the text form field. It’s doing this by looking for an instance
variable of the same name as the first argument you pass to the
helper. The second argument passed is the name of an attribute on
that instance variable. So, the easiest way to provide the value to
the text_field helper is to put this in your controller action:

@role = @user.role

What I haven’t tried, since I never really thought about it before
now, is if you change the value of the first argument to ‘user
[role]’, does the text_field helper know how to interpret that as:
use the role attribute of the user instance variable as this fields
container.

My guess is that it probably doesn’t. Another good reason to make a
@role instance variable is that doing so would allow you to
separately process validation errors for the role and the user.

-Brian