17

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?

1
  • No error message in the console? If it the condition isn't true? Why not just use disabled: !is_admin?? Jun 1, 2014 at 2:33

2 Answers 2

38

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.

2
  • Thanks! That worked, I wonder why disabled: true if not is_admin messed up when I was logged with the admin account. Jun 1, 2014 at 2:53
  • 1
    I actually explained the reason in the answer. Its like if condition is acting as a modifier on text field, so text field would only be displayed when condition in if condition is true, the condition in your case was if not is_admin?. When logged in with admin account, is_admin? returns true, so not is_admin? becomes false which is why text field is not shown as condition is false.
    – Kirti Thorat
    Jun 1, 2014 at 17:00
5

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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.