1

Rails 4.1.4, Ruby 2.1.2. Postgres.

I have a user model which has a roles attribute. The roles attribute is a postgres array type. I am trying to create a form with checkboxes of different role options, and a user can select which roles they fit into. If they select the 'director' checkbox, their roles attribute, now you should see:

@user.roles = ['director'].

I am trying to use a form_for, but maybe this is not possible.

Does anyone know how to do this?

form_for(@user) do |f|
    f.check_box :roles ...?
2

3 Answers 3

1

You can try this

 form_for(@user) do |f|
   f.collection_check_boxes(:roles, @user.roles, :id, :labeling_method )

more details

http://apidock.com/rails/v4.0.2/ActionView/Helpers/FormOptionsHelper/collection_check_boxes

Sign up to request clarification or add additional context in comments.

4 Comments

Seems you miss the third parameter , it should be a collection object of all roles.
Nope I did @user.roles ...it is form object ......so as you told collection_check_boxes(:post, :author_ids, Author.all, :id, :name_with_initial) but here form_for with form object f so f.collection_check_boxes :author_ids, Author.all, :id, :name_with_initial refer edgeapi.rubyonrails.org/classes/ActionView/Helpers/…
Ok! I'm wrong. But still a suggestion use some other roles collectioin instead of @user.roles. There will be no check_box displayed for a new user.
Thanks for your suggestion yes it should be good yes I can do but please see the question he already use @user.roles I thought it will be better to understand for him
1
form_for(@user) do |f|
  f.check_box :roles, User::ROLES #assuming you have a constant ROLES holding your roles.

editing due to comment

5 Comments

How would I do this with roles that are not active record objects? They are simply strings (i.e. I simply want to add the string 'director' or 'admin' to the roles array if that check box is selected). I don't think I understand how to set up a User::ROLES constant that responds to an :id method.
do you want to be able keep few roles in :role attribute, right? You can do f.check_box :roles, User::ROLES, {multiple: true }
Rails error: wrong number of arguments (2 for 4..6). No, simply strings within an array.
do you have this ROLES constant in User model?
probably @user.roles
0

Let's say you have some string constant in your User

<%= form.collection_check_boxes(:roles, USER::ROLES_STRINGS[access_if_you_need_from_this_constant_but_we_need_an_array_here].keys, :to_s, Proc.new{|l| USER::ROLE_STRINGS[access_if_you_need_from_this_constant_but_we_need_an_array_here][l]}) %>

Should work / get you close based on your structure!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.