Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

text_field disabled in Ruby on Rails

I have the following code to disable a text_field when a user is not an admin and it is working fine:

<div class="form-group">
<%= f.label :nome, "Genero" %>
<%= f.text_field :nome, class: "form-control", disabled: true if not is_admin? %>
</div>

But when a user is an admin the text_field just disappears. Does anyone know why this is happening and what I have to do?

like image 236
Vitor Vezani Avatar asked Jun 01 '14 02:06

Vitor Vezani


2 Answers

Assuming that is_admin? returns true or false, you can simply do

<%= f.text_field :nome, class: "form-control", disabled: !is_admin? %>

Currently, the if condition i.e., if not is_admin? is applied on the entire text field, which results in text field disappearance when is_admin? returns true and when the condition returns false text field is displayed.

like image 146
Kirti Thorat Avatar answered Sep 20 '22 07:09

Kirti Thorat


The specific reason that your code wasn't working as expected is an operator precedence issue - the if test is being applied to the whole text field, not just the disabled parameter.

The most direct solution to this (though not necessarily the best) is to wrap true if not is_admin? in parentheses:

<%= f.text_field :nome, class: "form-control", disabled: (true if not is_admin?) %>

Otherwise, the whole text field has the if applied to it, like this:

<%= (f.text_field :nome, class: "form-control", disabled: true) if not is_admin? %>

So it will be rendered only for non-admin users - i.e. when is_admin? is false.

Also, when it's rendered, it will always be disabled. (Which on the plus side, will make it harder for non-admins to abuse.)

like image 33
mwfearnley Avatar answered Sep 23 '22 07:09

mwfearnley