0

I have this form:

<%= form_for @user, url: admin_user_path(@user.id) do |f| %>
      <%= f.label :first_name %>
      <%= f.text_field :first_name %>
      <br>
      <%= f.label :last_name %>
      <%= f.text_field :last_name %>
      <br>
      <%= f.label :tags %>
      <%= f.text_field :tags_string %> 
      <%= f.submit "update", placeholder: "Update" %>
<% end %>

@user.tags is an array of strings, with possible ["A","B","C"] as possible tags. Some users have one, some have all of them...etc.

Being tags_string a method which converts tags in a string for having the user editing the form to change it if desired.

However, this is error prone, and I want the user to have the ability to chose between all possible tags having them in checkboxes.

What would I need to do in order to achieve this?

Thanks.

2 Answers 2

1

I'd first recommend using simple_form (git:plataformatec/simple_form) instead of form_for which will make this much easier for you!

You can write the form as:

<%= simple_form_for @user, url: admin_user_path(@user.id) do |f| %>
  <%= f.input :first_name %>
  <%= f.input :last_name %>
  <%= f.input :tags_string, as: :check_boxes, collection: ['A', 'B', 'C'] %> 
  <%= f.button :submit, value: 'Update' %>
<% end %>

Voila, you are all set! Are you serializing the array of tags or is Tag a model that has_many Users?

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

4 Comments

Sorry, I forgot to mention that I'm using Mongoid. That doesn't allow me to use simple_form: stackoverflow.com/questions/9755726/…
Gotcha, then you can just use the collection_check_boxes() method inside the form_for! I'd use it like: <%= collection_check_boxes(:tags_string, #method, TagsStrings.all, :id, :name) %>
:tags_strings would work if TagsString is a model and User has_many :tags_strings but I'd need to know more about how the connection is set up (like I mentioned before, serialized array vs. related models) to give you a more exact answer.
: tags_strings is a method in User collection, returning the user tags as a string: ["A","B","C"] -> "A,B,C".
0

You can probably loop possible tags and show the check-box for each tag. Your modified code looks like:-

  <% @user.tags.each do |tag| %>
        <%= check_box_tag 'tags_string[]', tag.name -%>
        <%= tag.name -%>
  <% end %>

Documentation reference for showing checked or not and other options available:- http://apidock.com/rails/ActionView/Helpers/FormTagHelper/check_box_tag

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.