Form select box from association


#1

Hello there,

I have the following models

class Bibliography < ActiveRecord::Base
has_and_belongs_to_many :gthemes, :join_table =>
“gthemes_bibliographies”
end

class Gtheme < ActiveRecord::Base
has_and_belongs_to_many :bibliographies, :join_table =>
“gthemes_bibliographies”
end

I want to include in the bibliography edit page a select box with all
the gthemes and i want the members of @bibliography.gthemes to be
marked as selected

I 'm using this in bibliography/_form.rhtml:

<%= select(‘bibliography’, ‘gthemes’ , Gtheme.find(:all).collect{ |gt|
[ gt.name, gt.id]}, {}, {:multiple => true}) %>

but it doesn’t mark the current gthemes as selected, any ideas?

Thanks in advance,
Christos


#2

On Mar 13, 4:02 pm, “Trochalakis C.” removed_email_address@domain.invalid
wrote:

has_and_belongs_to_many :bibliographies, :join_table =>
[ gt.name, gt.id]}, {}, {:multiple => true}) %>

but it doesn’t mark the current gthemes as selected, any ideas?

Thanks in advance,
Christos

I also tried using the form_for helper but the problem still exists

<% form_for :bibliography, @bibliography, :url => { :action =>
“update” } do |f| %>
Bgthemes: <%= f.select :gthemes, Gtheme.find(:all).collect {|c|
[c.name, c.id]}, {}, {:multiple => true} %>
<%= submit_tag ‘Save changes’ %>
<% end %>


#3

On Mar 13, 5:46 pm, “Trochalakis C.” removed_email_address@domain.invalid
wrote:

has_and_belongs_to_many :gthemes, :join_table =>
marked as selected

I also tried using the form_for helper but the problem still exists

<% form_for :bibliography, @bibliography, :url => { :action =>
“update” } do |f| %>
Bgthemes: <%= f.select :gthemes, Gtheme.find(:all).collect {|c|
[c.name, c.id]}, {}, {:multiple => true} %>
<%= submit_tag ‘Save changes’ %>
<% end %>

For the record, I didn’t manage to find a “magic way” to do it, but
this is a nice and working solution:

<%= select_tag ‘gthemes[]’,
options_from_collection_for_select(@gthemes, ‘id’, ‘name’,
@bibliography.gtheme_ids ),
{:multiple => true, :class => “wide”}
%>


#4

On Mar 20, 8:30 pm, “Trochalakis C.” removed_email_address@domain.invalid
wrote:

For the record, I didn’t manage to find a “magic way” to do it, but
this is a nice and working solution:

<%= select_tag ‘gthemes[]’,
options_from_collection_for_select(@gthemes, ‘id’, ‘name’,
@bibliography.gtheme_ids ),
{:multiple => true, :class => “wide”}
%>

@gthemes = Gtheme.find(:all)