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😉

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay