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?
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With