views:

30

answers:

1

Hello I have a form in witch users can add their working hours view them and edit them (All in one page). When adding working hours the user must select a project from a dropdown list. In case the action is adding a new hour record the dropdown field should remain empty (not selected) in case the action is edit the dropdown field should be selected with the appropriate value. In order to overcome this challenge I wrote the following code

<% if params[:id].blank?%>
     <select name="hour[project_id]" id="hour_project_id">
         <option value="nil">Select Project</option>
         <% @projects.each do|project|%>
             <option value="<%=project.id %>"><%=project.name%></option>
         <% end%>
    </select>
 <% else %>
   <%= select('hour','project_id', @projects.collect{|project|[project.name,project.id]},{:prompt => 'Select Project'})%>
 <% end %>

So in case of save action I did the dropdown list only with html, and in case of edit action I did it with the collect method. It works fine until I tried to code the errors. The problem is that when I use the error method: validates_presence_of :project_id it didn't recognize it in the html form of the dropdown list and don’t display the error message (its working only for the dropdown with the collect method).

I will deeply appreciate your instructions and help in this matter

+1  A: 

options_from_collection_for_select(collection, value_method, text_method, selected = nil) is your friend:

<%= select('hour','project_id', options_from_collection_for_select(@projects, :id, :name, @hour.project_id),{:prompt => 'Select Project'})%>

If there is an @hour object and it is new and therefore doesn't have a project_id the value will be nil and nothing will be selected - alternatively the value of the @hour will be selected.

Apie
It didn’t work for me. Maybe because all my operation are done in one page. When the user selects the project and clicks on the save button he is redirected again to the same page. When I tried your suggestion<%= select('hour','project_id', options_from_collection_for_select(@projects, :id, :name, @hour.project_id,),{:prompt => 'Select Project'})%>The dropdown list was always selected.
winter sun
I finally understood my problem it appears that in my control after performing the create operation i didn't call to @hour=Hour. newso when the form page was reloaded it reloaded with Hour.new(params[:hour]). i change it to @hour=Hour.new and it is working!!!!!!
winter sun