Better way for select list for belongs_to?

I’m currently doing all of this just to have a drop-down list of
Courses for a particular student:

===== edit template =====
<%= f.select :course, @courses, :selected => @student.course.id %>

===== students controller =====
def edit
@student = Student.find(params[:id])
@page_title = “Edit #{@student.full_name}”
@courses = Course.find(:all).collect { |c| [ c.name, c.id ] }
end

def update
@student = Student.find(params[:id])
@student.attributes = params[:student]
@student.course = Course.find(params[:student][:course])

respond_to do |format|
  if @student.save
    flash[:notice] = "#{@student.full_name} was successfully

updated."
format.html { redirect_to students_url }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @student.errors.to_xml }
end
end
end

Students :belongs_to :course, and Course :has_many :students. I’ve
tried several different ways of doing this, and this has been the
first that’s actually successful. Having already tried the bad way,
I’d like to think this is the ugly way, and hope someone has a
suggestion on the Good Way? :slight_smile: Any help would be appreciated.

Thanks!

How about:

===== edit template =====
<%= f.select :course_id, @courses %>

===== students controller =====
def edit
@student = Student.find(params[:id])
@page_title = “Edit #{@student.full_name}”
@courses = Course.find(:all).collect { |c| [ c.name, c.id ] }
end

def update
@student = Student.find(params[:id])
@student.attributes = params[:student]

respond_to do |format|
  if @student.save
    flash[:notice] = "#{@student.full_name} was successfully

updated."
format.html { redirect_to students_url }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @student.errors.to_xml }
end
end
end

When I get that, I get an exception: Course expected, but got String

Oops… forgot to mark attr_accessible :course_id. :slight_smile: Doing what you
suggested works as expected. I tried a lot of different combinations
to get what I wanted, I just must have missed this one. Thanks!