Forum: Ruby on Rails collection_select not selecting item, unless...

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
9be5d718d17f374932ae41a434174e6a?d=identicon&s=25 Nathan Fiedler (Guest)
on 2007-07-20 10:01
(Received via mailing list)
I'm fairly new to Rails, so this could just be my stupidity rather than

My app has two simple models: record (id, category_id, ...) and
category (id, name). In my generated scaffold _form.html for the
record model, I have the following collection_select:

<%= collection_select 'record', 'category', @categories, :id, :name %>

The option tag is properly populated, but the current category for the
record being edited is not selected. However, if I change the above
line to:

<%= collection_select 'record', 'category_id', @categories, :id, :name

Then it will select the proper category in the HTML form. But, when I
try to save, it fails with an exception (ActiveRecord::RecordNotFound
in RecordsController#update => "Couldn't find Category without an

Here's the edit and update methods from RecordsController:

  def edit
    user = User.find(session[:user_id])
    @record = user.records.find(params[:id])
    @categories = user.categories.find(:all, :order => 'name')

  def update
    user = User.find(session[:user_id])
    @record = user.records.find(params[:id])
    # Replace the category id with the actual Category.
    params[:record][:category] =
    if @record.update_attributes(params[:record])
      flash[:notice] = 'Record was successfully updated.'
      redirect_to :action => 'show', :id => @record
      render :action => 'edit'

Any ideas what I'm doing wrong?



P.S. You can browse all of my marvelous code here: => click on "manifest" and
you'll see the typical Rails app structure.
4765b690d8d04b089b0a7b0ee7768ebc?d=identicon&s=25 Stijn Pint (spint)
on 2007-07-20 10:28
If you change your collection select to "category_id", you have to
change it in your controller too ofcourse, did you do that ?
so params[:record][:category] should be params[:record][:category_id]

9be5d718d17f374932ae41a434174e6a?d=identicon&s=25 Nathan Fiedler (Guest)
on 2007-07-20 17:12
(Received via mailing list)
Good point, that would address the error. Thanks.

However, the question remains: why do I have to change this to be
different than every single example of collection_select I have found
so far, including the AWDWR book, postings on this list, and the Rails
wiki itself?


This topic is locked and can not be replied to.