Select options for HABTM?

I’ve looked through the docs and the wiki and can’t
figure out how to go about generating select options
and the update function for an item that has a HABTM
relationship.

I have a ‘parks’ table and the park model has a HABTM
to the ‘states’ table. On the park edit page, I’d like
a multiple select box to appear with all states show,
and those in the parks_states table selected. Does
anybody have some example code?

Thanks!
csn


Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around

CSN <cool_screen_name90001@…> writes:

I’d don’t use the multiple-choice select very often, but something like:

options_from_collection_for_select(State.find(:all), :id, :name,
@park.states.collect {|s| s.id})

should work, right? Assuming State is your model, and the value of the
option is
State#id, and the text is State#name, and @park is your current Park.

— KW [email protected] wrote:

I have a ‘parks’ table and the park model has a
but something like:

options_from_collection_for_select(State.find(:all),
:id, :name,
@park.states.collect {|s| s.id})

should work, right? Assuming State is your model,
and the value of the option is
State#id, and the text is State#name, and @park is
your current Park.

Yeah - here’s what I came up with:

edit template

<%= options_from_collection_for_select State.find(:all, :order=>'name'), 'id', 'name', @park.states.collect {|state| state.id } %>

update method

@park = Park.find(params[:id])

@park.state_ids = params[:park_states]

@park.update_attributes(params[:park])

if @park.errors.empty?
redirect_to :action=>:list
else
render :action=>:edit
end

If anybody can improve and/or simplify it, please feel
free! Perhaps I’ll stick it in the wiki.

csn


Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around