I am trying to outline around collection_selects in Rails. I can fill in the drop-down list from the database table, send the selected parameter and show the result. However, I cannot figure out how to show the selected option in the drop-down list when the user wants to edit the entry.
Here is an excerpt from my view code:
<p>
<%= f.label :Status %><br />
<%= f.text_field :status %>
</p>
<p>
<%= f.label :Manager %><br />
<%= f.collection_select(:manager, @managers, :id, :name, {:include_blank => true}) %>
</p>
Here is my controller code:
class ProjectsController < ApplicationController
before_filter :require_user
def index
@projects = Project.all
respond_to do |format|
format.html
format.xml { render :xml => @projects }
end
end
def show
@project = Project.find(params[:id])
projectid = params[:id]
@evidence = Evidence.find(:all, :conditions => ["projectid = ?", projectid])
respond_to do |format|
format.html
format.xml { render :xml => @project }
end
end
def new
@project = Project.new
@managers = Manager.find(:all)
respond_to do |format|
format.html
format.xml { render :xml => @project }
end
end
def edit
@project = Project.find(params[:id])
@managers = Manager.find(:all)
end
def create
@project = Project.new(params[:project])
respond_to do |format|
if @project.save
flash[:notice] = 'Project was successfully created.'
format.html { redirect_to(@project) }
format.xml { render :xml => @project, :status => :created, :location => @project }
else
format.html { render :action => "new" }
format.xml { render :xml => @project.errors, :status => :unprocessable_entity }
end
end
end
def update
@project = Project.find(params[:id])
respond_to do |format|
if @project.update_attributes(params[:project])
flash[:notice] = 'Project was successfully updated.'
format.html { redirect_to(@project) }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @project.errors, :status => :unprocessable_entity }
end
end
end
def destroy
@project = Project.find(params[:id])
@project.destroy
respond_to do |format|
format.html { redirect_to(projects_url) }
format.xml { head :ok }
end
end
end
And here is the code for my models:
class Manager < ActiveRecord::Base
has_many :projects
end
class Project < ActiveRecord::Base
belongs_to :manager
validates_presence_of(:name, :reference, :client, :status)
validates_uniqueness_of (:reference)
end
Any help is greatly appreciated.
Thank!
source
share