Partial form in rails 3 needing different link depending on New or Edit

Joel Friedlaender picture Joel Friedlaender · Dec 8, 2010 · Viewed 7.6k times · Source

I have a basic setup of views that was generated by the Rails 3 scaffolding. It gives me a partial view _form.html.erb. Both my edit.html.erb and my new.html.erb render this partial view.

In the partial view, I want to have a link_to that goes to different paths depending on if it is being rendered by the new or the edit view.

Is there an easy way to do this?

My code looks like this currently, but does not allow for different paths.

<%= f.submit %> or <%= link_to 'Go back', models_path %>

If it helps, I am trying to send them back to the page they came from (they come from different places for add and edit)

Answer

nanda picture nanda · Dec 8, 2010

You can use form.object.new_record? instead of params[:action] to know if you are editing or creating (edit view versus new view).

eg:

<%= simple_form_for(@item) do |f| %>  
    <% if @item.new_record? %>  
       <%= f.input :lost_time, input_html: { value: DateTime.now } %>  
    <% else %>                      
       <%= f.input :lost_time, input_html: { value: @item.lost_time } %>    
    <% end %>
<% end %>