Flowdock

Notes posted by ctagg

RSS feed
May 2, 2009
0 thanks

Setting name and id for select_tag

Sometimes you need to use select_tag instead of select (because you’re after more control or need to use optgroups, for example), but still want the id/name conventions that select would give.

In this case, all you need to do is set the first parameter to whatever would be produced by select, and it’ll take care of the id and name attribute automatically, and thus ensure the form data is parsed correctly after submission.

For example, if you want to do something like:

form_for :comment do |f|
 f.select :article_id ...

which would give a select tag with id of “comment_article_id” and a name attribute of “comment[article_id]”, which be parsed into the params hash of:

'comment' => {'article_id' => ...

you can instead do

form_for :comment do |f|
 select_tag 'comment[article_id]' ...

which will give the same id and name attributes for the select tag and hence the same params hash in the controller