0

Hi I have the following dropdown form where I want to preselect dropdown value depending on whether a user is an admin or not.

However the u.admin seems not doing the job. Is there a way I can achieve this with option_for_select?

<%= form_tag users_path(u), method: :patch do %>
    <%= select_tag :admin, options_for_select([['Admin user', true], ['Normal user', nil]], u.admin) %>
    <%= submit_tag 'Update', class: "btn btn-sm btn-primary" %>
<% end %>

below is my usermodel

create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "avatar"
    t.string "lastname"
    t.string "firstname"
    t.string "description"
    t.boolean "admin"
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end
Eric Chuhao Chan
  • 367
  • 1
  • 3
  • 5
  • Have you tried using `false` instead of `nil`? – BM5k Jul 11 '18 at 01:26
  • Hi @BM5k yes i have tried false as well. The reason why I changed to nil was because the default value in the admin column is nil. – Eric Chuhao Chan Jul 11 '18 at 02:19
  • 1
    You should likely address that - far better to have the db default to `false` for the admin column to avoid any confusion like this. – SRack Jul 11 '18 at 12:14
  • 1
    Too late to edit the above, but good [examples here](https://stackoverflow.com/questions/8627156/adding-default-true-to-boolean-in-existing-rails-column). – SRack Jul 11 '18 at 12:20

2 Answers2

1

Looks like the value is wanting a string to match the array (which seems a little odd, but what can ya do?). Therefore, you can call:

<%= form_tag users_path(u), method: :patch do %>
    <%= select_tag :admin, options_for_select([['Admin user', true], ['Normal user', nil]], u.admin.to_s) %>
    <%= submit_tag 'Update', class: "btn btn-sm btn-primary" %>
<% end %>

This avoids having to clutter the view with an additional variable. Hope it helps :)

SRack
  • 11,495
  • 5
  • 47
  • 60
0

After several attempts, I figured out a way to store u.admin as a variable for each user. Here is the code

<%= form_tag users_path(u), method: :patch do %>
    <% @admin = u.admin %>
    <%= select_tag :admin, options_for_select([['Admin user', true], ['Normal user', nil]], "#{@admin}") %>
    <%= submit_tag 'Update', class: "btn btn-sm btn-primary" %>
<% end %>
Eric Chuhao Chan
  • 367
  • 1
  • 3
  • 5