I have a very simple Project form with a name field and a select box with various Client names in it:
<%= f.label :name %><br/>
<%= f.text_field :name %>
<%= f.label :client_id %><br/>
<% options = current_user.clients.all.map { |client| [client.name, client.id] } %>
<%= f.select(:client_id, options, {:prompt => 'Select...'}) %>
Now when a user hits submit without actually selecting a Client from the select box, an error is returned saying that a Client with ID ” ” cannot be found.
Is there any way to change my controller code so that it works?
def create
client = current_user.clients.find(params[:project][:client_id])
@project = client.projects.build(params[:project])
if @project.save
flash[:success] = "Project created."
redirect_to @project
else
render :action => "new"
end
end
It’s the local client variable that causes the trouble but I don’t know how to fix it so that errors will be handled by the validation methods.
Above code is trying to fetch a
client object by passing id as nil. Following code should work, provided there is avalidation for client recordbefore saving project record.