9

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)

Joel Friedlaender
  • 2,191
  • 1
  • 18
  • 24

3 Answers3

48

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 %>
whyisyoung
  • 316
  • 5
  • 16
nanda
  • 1,313
  • 9
  • 16
5

I am not that familiar with rails 3. But hope this works for you

<% if params[:action] == 'new' %>
    # code for new
<% elsif params[:action] == 'edit' %>
    # code for edit
<% end %>

GOOD LUCK :D

Srushti
  • 314
  • 2
  • 8
  • This is not the best solution since it won't display any link at all when validation fails and the action is create or update – axelarge Aug 13 '11 at 15:46
0

Have a look at link_to(:back).

That might be what you need here.

Milan Novota
  • 15,506
  • 7
  • 54
  • 62
  • This is not the best solution for security and logical reasons. "When using redirect_to :back, if there is no referrer, RedirectBackError will be raised. You may specify some fallback behavior for this case by rescuing RedirectBackError." – nanda Dec 09 '10 at 00:28
  • I later refactored and ended up passing the path as a local parameter to the form, that way if I use the form in a variety of places, I have full control. – Joel Friedlaender Feb 03 '11 at 22:38