问题
1.How can i make a text field non-editable (readable=false) while editing record
My Form View Code
<div class="field">
<%= f.label t :profile_name %><br />
<%= f.text_field :profile_name %>
</div>
2.How can i make a field visible while editing a record. I have a field in the database table that i just want to display to fill in while editing the record however while create a new record that field not be visible.
RESOLVED:
Never Mind Guys i got the solution,
1.
<div class="field">
<%= f.label t :profile_name %><br />
<%= f.text_field :profile_name, :readonly => f.object.persisted? %>
</div>
2.
<% if f.object.persisted?%>
<div class="field">
<%= f.label t :another_field %><br />
<%= f.text_field :another_field%>
</div>
<% end %>
回答1:
If you want your textbox to non-editable, you can do with little css or in the front end like the following:
<div class="field">
<%= f.label t :profile_name %><br />
<%= f.text_field :profile_name, disabled: disabled %>
</div>
or add :readonly => true instead of disabled. so,
<div class="field">
<%= f.label t :profile_name %><br />
<%= f.text_field :profile_name, readonly: true %>
</div>
Add disabled in your view to make a non-editable text box. We can do in css as well if its not work. Just let me know if its worked or not.
回答2:
Answer for those who find this. My problem was very close. I had a field I wanted to display, but not have editable. I was using devise, and only allow email and password to be set via devise view.
1) Disable editing in the form (this step provides zero security):
<%= f.text_field :email, readonly: true %>
2) Prevent shenanigans on by the client (this step is the actual protection):
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
# params.require(:user).permit(:email, :phone_number, :password, :password_confirmation)
# email and password must be edited via devise controller
params.require(:user).permit(:phone_number)
end
2b) Alternatively, you could just remove the value from the edit set:
def update
params['user'].delete('email')
...
end
来源:https://stackoverflow.com/questions/14830223/ruby-on-rails-make-text-field-non-editable-and-display-another-field-while-edit