DEV Community

Thibault
Thibault

Posted on

Disabled: true vs Readonly: true in Rails

What did i want to accomplish:

I had a rails form where i wanted one of the required fields to auto fill with some values.

<% if @issue.safe_attribute? 'subject' %>
<p> <%= f.text_field :subject, value: @issue.project.name, :size => 80, :maxlength => 255, :required => true %></p>
<% end %>
Enter fullscreen mode Exit fullscreen mode

The goal being, a user editing the form should not be able to edit this specific field.

If you're like me, your first thought would be to add disabled: true to the code. This disabled the field but it was triggering validation errors saying the field can't be blank.

After reading about the disabled option, i realized disabled elements are not submitted with the form(thus triggering validation) while readonly as its name says it, cannot be modified by a user interaction.

More info here

How did i accomplish it:
Replace disabled: true with readonly: true

Result:

<% if @issue.safe_attribute? 'subject' %>
<p> <%= f.text_field :subject, value: @issue.project.name, readonly: true, :size => 80, :maxlength => 255, :required => true %></p>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Moral of the story: Should've taken HTML course seriously😉

Top comments (0)