How to set a field read only in rails 3.1.0 views?

user938363 picture user938363 · Feb 2, 2012 · Viewed 25.5k times · Source

My question is how to set a field in rails form read only. The following is a selection box in quotes controller. Users are not allowed to change the selection.

  <% @quote.test_items.each do |t| %> 
    <%= f.association :test_items, :label => false, :selected => t.id %>
  <% end %>

The app uses simple_form. Thanks so much.

Answer

gk0r picture gk0r · Aug 10, 2012

I've encountered a similar problem, thankfully, there is a simple resolution.

The basic issue is that if you use :disabled => true with simple_form you will not see that value back in the controller. When you pass an object from HTML form to later bind it to the model - you need all of those attributes. The :disabled => true however does not pass any such attribute.

The solution to this is to use :readonly => true - it will protect the field from user entry and it will still pass the param value back to the controller so you can bind everything to your model.

Good luck.

See https://github.com/plataformatec/simple_form/pull/367