editing ActiveRecord collection with related drop-downs using related_select_forms
Another problem setting the HTML name
attribute when editing a collection of ActiveRecord objects in a Rails application. This time I was using the related_select_forms
plugin to build related drop-down (select) lists. The plugin which creates all the necessary javascript to dynamically reload the second list according to the selection in the first list is kindly provided by Dimitrij Denissenko and available here.
After a bit of research I found that the name
argument can be arbitrarily defined in the html_options
hash passed as the final argument to the select list helper (see the docs here).
First I had to build up the name
strings for the html in the format:
product[1424][field_name]
theme_name = "product[" + @product.id.to_s + "][theme_id]"
sub_theme_name = "product[" + @product.id.to_s + "][sub_theme_id]"
<%= select(:theme, :id, theme_list, {},
{ :name => theme_name } ) %>
second select list
<%= related_collection_select(
:sub_theme, :id, [:theme, :id], SubTheme.live_list,
:id, :name, :theme_id,
{},
{ :name => sub_theme_name } ) %>
NB: there is a slight gotcha here with the hashes. The first (empty) hash is the options{}
hash used only for {:include_blank => true}
, the second hash is used to set whatever HTML attributes you need, eg: { :selected => @product.sub_theme_id, :multiple => true, :name => sub_name }
. You must include the first hash, empty if you don’t want to use :include_blank => true
.