Do not show form field if action is being edited

I have a rails form that makes a partial list of fields for creating a new user. I also use these fields to render the form. I wonder if it is possible not to show a specific field (i.e. Department) in the editing form, because I do not want to give users the opportunity to change the department?

+5
source share
4 answers

Can you use persistent method ? to make sure that it is not a new record to be inserted or even uses the new_record method ? which will return true if the record is not saved in your "New record" database. ex ::

<%= f.text_field :department if @user.persisted? %> or <%= f.text_field :department unless @user.new_record? %> 

another way is to check the action itself, which also gives you control over the controller, if you visualize a partial view from another view and want to limit it to a specific controller, they are stored in:

 params[:controller] -->> contains the name of the controller ex. UserController that you just hit on params[:action] -->> contains the action name ex. new or edit 
+9
source

Just put in your form:

 <%= f.text_field :department unless @user.new_record? %> 
+2
source

If params [: action] is edit, then do not display this field using display none

+1
source

This can be done in many ways.

I usually do it like

 if !@user.new _record? # department field. end 
+1
source

Source: https://habr.com/ru/post/1206473/


All Articles