Search code examples
ruby-on-railsruby-on-rails-3tagssimple-form

How do I use collection_check_boxes with an Array?


So I'm using simple_form for building my forms, this is not a requirement though.

What I am trying to do is using simple_forms collection_check_boxes and pass it an array.

I am storing my tags in configatron:

configatron.tags = [{:name => "wheels", :tagtype => "property"}, {:name => "roof", :tagtype => "property"}, {:name => "doors", :tagtype => "property"}]

Here is my Tag model:

class Tag
  include Mongoid::Document
  embedded_in :taggable, polymorphic: true

  field :name
  field :tagtype
end

Here is what I've tried:

<%= f.collection_check_boxes :tags, @tags, @tags.map{|tag| tag.name}, @tags.map{|tag| tag.name} %>

where @tags is set to configatron.tags in controller

I simply want to make the collection_check_boxes work and then on before_save build the tag and embed it in the current resource.

I've read somewhere that you can map into the collection passed in and pick the content of an item of that collection. If i get it right, override the value_method? Can't seem to remember how you can do this though. I also want to pass in the current tags of this resource :collection => resource.tagsso that these tags is checked on rendering.

Is there any way of doing this? How would I manipulate the form_builder to make this possible, if so, how? Should I take another approach?

Sidenote: This functionality should work with backbone too, in some places backbone would be used for adding tags.


Solution

  • After checking simple-form docs, I think you need to pass in the value_method and label_method as symbols to collection_check_boxes

    Such as this:

    <%= f.collection_check_boxes :tags, @tags, :name, :name %>
    

    Does that work?