Forum: Ruby on Rails select options for HABTM?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
81194a50c0f9bd95d7832a77fdf371bd?d=identicon&s=25 CSN (Guest)
on 2006-02-10 00:08
(Received via mailing list)
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
http://mail.yahoo.com
27f8beb57f4d56d328749b51ac886d2c?d=identicon&s=25 KW (Guest)
on 2006-02-10 02:12
(Received via mailing list)
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.
81194a50c0f9bd95d7832a77fdf371bd?d=identicon&s=25 CSN (Guest)
on 2006-02-10 02:24
(Received via mailing list)
--- KW <kianwright@pfima.com> 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
<select name="park_states[]" size=10 multiple>
  <%= options_from_collection_for_select
    State.find(:all, :order=>'name'), 'id', 'name',
    @park.states.collect {|state| state.id } %>
</select>

# 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
http://mail.yahoo.com
This topic is locked and can not be replied to.