On Apr 7, 5:21 am, LukeG <[email protected]> wrote:
> I'm a noob. I've trolled the web and groups for help, but I just don't
> know enough Rails to apply the solutions to my particular problem. I
> even got the screencast from Pragmatic Programmers, but still no dice.
>
> I'm having a problem getting my collection_select to initialize with a
> previously stored value. I have items and categories, with many items
> to one category. When I edit an item, the category list populates
> correctly, but I cannot figure out how to set the default to whatever
> category was already stored for that item.
collection_select is like the various model helpers in that you do
collection_select 'instance_variable_name', 'method_name', ...
ie in this instance collection_select 'observation',
'category_id', ...
Seeing as how you've already got a form_for setup, you should be able
to do f.collection_select 'category_id', ...
Calling it on the form builder means you don't need to tell rails
which object you are working with.
Fred
>
> Running Rails 2.3.2, here is the code:
>
> *controller:*
> def edit
> @observation = Observation.find(params[:id])
> end
>
> *view:*
> <%= f.label "Category" %><br />
> <%=
> collection_select(:observation_category_id,
> @category_id,
>
> ObservationCategory.find(:all),
> :id,
> :name,
> {:selected =>
> @observation.observation_category_id})
> %>
>
> *models:*
> class Observation < ActiveRecord::Base
> attr_accessible :name, :icon_url, :observation_catategory_id
> belongs_to :observation_category
> end
>
> class ObservationCategory < ActiveRecord::Base
> has_many :observations
> end
>
> *html:*
> <label for="observation_Category">Category</label><br />
> <select id="observation_category_id_" name="observation_category_id
> []"><option value="1">exercise</option>
> <option value="2">finance</option>
> <option value="3">nutrition</option>
> <option value="4">mood</option>
> <option value="5">energy</option>
>
> <option value="6">focus</option>
> <option value="7">sleep</option>
> <option value="8">junk_cat</option>
> <option value="9">satiation</option></select>
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---