ZedBee
ZedBee

Reputation: 2378

rails simple_form fields not directly related to the model

I am new to rails and using simple form for the first time. I have an article model and tag model. @article.tags give me all the tags related to a the specific article.

I am trying to build a form (like stackoverflow) where the tags can be entered as comma separated values. Since the tags are only names as string values and not objects, how to read these when the form is posted and how to render the html input for this tags textbox using simple form. Also how can I get the tags as comma separated value in edit form.

Upvotes: 0

Views: 67

Answers (2)

davidwessman
davidwessman

Reputation: 1228

I would recommend: Select2 through the select2-rails gem.

Especially with what they call Tagging.

I implement it by loading a js:

function select2() {
  $('.select2').select2({
    theme: 'bootstrap',
    width: '100%'
  });
}

function select2Tags() {
  $('.select2_tags').select2({
    tags: true,
    theme: 'bootstrap'
  });
}

$(select2);
$(select2Tags);

And in the form I would do:

<%= f.association :tags, collection: Tag.all,
                               input_html: {class: 'select2'} %>

But this would require the tags to be created before hand.

Upvotes: 1

Ronan Lopes
Ronan Lopes

Reputation: 3398

I would suggest you take a look at the cocoon gem (https://github.com/nathanvda/cocoon). It is used for nested fields, so you can dynamically add new fields (in this case, new inputs for tags). It is not so complicated to use and it's kinda nice for user experience.

Upvotes: 1

Related Questions