Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 805
user938363 Avatar asked Feb 02 '12 22:02

user938363


People also ask

What are readonly fields?

In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class. A readonly field can be assigned and reassigned multiple times within the field declaration and constructor.

Are readonly fields submitted?

Note: A form will still submit an input field that is readonly, but will not submit an input field that is disabled!


2 Answers

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

like image 84
gk0r Avatar answered Sep 30 '22 11:09

gk0r


I believe you'd just pass in :disabled => true. It's been my experience that options 'just work' with simple_form. So in your case:

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

From the simple_form github repo:

It is also possible to give the :disabled option to SimpleForm, and it'll automatically mark the wrapper as disabled with a css class, so you can style labels, hints and other components inside the wrapper as well.

like image 28
Matthew Lehner Avatar answered Sep 30 '22 11:09

Matthew Lehner