conditional based on the controller action for new

2019-07-24 09:34发布

问题:

I have a form rendered in the new and edit views:

<%= simple_form_for(@course, html: {class: "form-horizontal"}) do |f| %>

Since my edit form should be slightly different: simple_form_for([@category, @course]), is there a way to write a conditional based on the controller action (edit or new) ?

# if controller action is new

<%= simple_form_for(@course, html: {class: "form-horizontal"}) do |f| %>

#if controller action is edit

<%= simple_form_for([@category, @course], html: {class: "form-horizontal"}) do |f| %>

回答1:

You can use action_name

<% if action_name == 'edit' %>
  #
<% else %>
  #
<% end %>

Or to be really safe, use controller_name also

<% if controller_name == 'cources' && action_name == 'edit' %>


回答2:

You can use this code:

- array_object = @course.new_record? ? [@course] : [@category, @course]

Or

- array_object = action_name == 'new' ? [@course] : [@category, @course]

Then do the following:

<%= simple_form_for(array_object, html: {class: "form-horizontal"}) do |f| %>

Read about new_record? helper method