Associations don't work with FormHelpers?

Hi,

I am trying to use an association in a form helper, like this:

<%= text_field "group.moderator", "id" %>

I get this error:    `@group.moderator' is not allowed as an instance variable name

Here is how I defined the models:

   class Moderator < ActiveRecord::Base       has_many :groups    end

   class Group < ActiveRecord::Base       belongs_to :moderator    end

How can I use associations in form helpers?     Thanks,

David

The call is

   <%= text_field :group, :moderator_id %>

assuming that's the foreign key in "groups". Nevertheless it is unsual to ask the user for an ID, normally you use a combo.

If the number of groups is too large for the combo to be usable some kind of auto completer is handy, but strings are not good to identify models. I wrote a helper that encapsulates a widget that mixes the auto completer with a hidden field for the key, I plan to polish it a release it as a plugin.

-- fxn

Xavier Noria wrote:

> I am trying to use an association in a form helper, like this: > > <%= text_field "group.moderator", "id" %> > > I get this error: > `@group.moderator' is not allowed as an instance variable name > > Here is how I defined the models: > > class Moderator < ActiveRecord::Base > has_many :groups > end > > class Group < ActiveRecord::Base > belongs_to :moderator > end

The call is

   <%= text_field :group, :moderator_id %>

assuming that's the foreign key in "groups". Nevertheless it is unsual to ask the user for an ID, normally you use a combo.

If the number of groups is too large for the combo to be usable some kind of auto completer is handy, but strings are not good to identify models. I wrote a helper that encapsulates a widget that mixes the auto completer with a hidden field for the key, I plan to polish it a release it as a plugin.

-- fxn

Actually, I want to display other fields in the moderators table, and traverse the association, like this: <%= text_field "group.moderator", "login" %> or <%= text_field "group", "moderator.login" %> where "login" is an atttribute of the "moderator" which is associated with the "group". Neither of these approaches works, but "@group.moderator.login" is a valid attribute.

Any ideas?

Thanks,

David

Helpers like text_field have this signature

   text_field(object, method, ...)

where "object" is the name of an instance variable in the view (idiomatically a symbol), and "method" the name of an accessor. Behind the scenes, the helper gets the variable dynamically and sends() method to it. With that call the helper sets the initial value of the widget, and constructs the name "object[method]". That's very handy, because most of the time is just what you need.

You need to switch to the generic *_tag family of helpers for extra flexibility, in this case text_field_tag.

-- fxn