开发者

ruby on rails-Problem with the selection form helper

开发者 https://www.devze.com 2022-12-23 09:46 出处:网络
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

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消