简体   繁体   中英

Rails replace text_field from _form by text_field from edit

I'm super fresh with Rails views

I've made rails app by rails new scaffold where inside of _form.html.erb was below code:

<%= form_with(model: property, local: true) do |form| %>

(...)

  <div class="field">
    <%= form.label :status %>
    <%= form.text_field :status %>
  </div>

(...)

Because I need to have default value for :status inside of new.html.erb I've modified _form.html.erb

    <%= form.label :status %>
    <%= form.text_field :status, value: 'planned', readonly: true  %>

Which has the effect of edit.html.erb where I rendered _form.html.erb because I need all the other fields from _form .

edit.html.erb

<h1>Editing Property</h1>

<%= render 'form', property: @property %>

<%= link_to 'Show', @property %> |
<%= link_to 'Back', properties_path %>

Is there a way to replace only this form.text_field:status from _form inside of edit.html.erb and the other fields leave like it?

You could achieve it by passing extra params to _form.html.erb :

# new.html.erb
<%= render 'form', extra_params: {value: 'planned', readonly: true} %>

# _form.html.erb
<%= form.text_field :status, local_assigns[:extra_params] || {}  %>

Or just in _form.html.erb :

# _form.html.erb
<% extra_params = @property&.persisted? ? {} : {value: 'planned', readonly: true} %>

<%= form.text_field :status, extra_params %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM