Rails hides action-based form field

I am making a form that will have several fields, and one of them should have a default value that is not displayed if the resource is created. But if it is being edited, the field should be displayed. So I try something like this:

<%= form_for(@task) do |f| %> <div class="field" id="v_field"> <%= f.label :v_field, "Always visible field." %> <%= f.text_field :status %> </div> <% if params[:action] != "new" %> <div class="field" id="default_field"> <%= f.label :default_field, "Default field (should be invisible for new resources only)." %> <%= f.text_field :status %> </div> <% end <% end %> 

But that will not work. I also tried to change the controller settings as follows:

 format.html { :except => [:default_field] } 

But that will not work.

Please tell me which comparison should be used in the state? Thanks.

+6
source share
1 answer

If you follow the usual Rails conventions, you will display this form either using the new or edit methods in the task controller.

For a new one, a new (empty) task is created; for editing an existing one, it is selected from the database.

A simple test would be to see if there is still an id task.

 <% if @task.id %> ... <% end %> 

You better look at the state of the object that you are manipulating, rather than at the actions taken by the user to get there.

+7
source

All Articles