Rails3 acts_as_taggable with a form

一个人想着一个人 提交于 2019-12-10 11:43:53

问题


I've just started working with the acts_as_taggable gem. Really liking it so far, but I am a bit unclear about how to use this gem with a form.

class Photo < ActiveRecord::Base
  acts_as_taggable_on :tags
end

In my form for Photos I am trying to implement a series of checkboxes for the user to assign tags to their photo:

<%= f.label :tag_list %>
<%= f.check_box :tag_list, "landscape" %>
<%= f.check_box :tag_list, "people" %>

When viewing the form I get this error:

NoMethodError in Photos#edit
...line #19 raised:

undefined method `merge' for "landscape":String
Extracted source (around line #19):

18:     <div class="float_tag">
19:       <%= f.check_box :tag_list, "landscape" %>

Any thoughts as to how I should create my form?


回答1:


I'm assuming your <form> looks something like this:

<%= form_for(@photo) do |f| %>
  <%= f.label :tag_list %>
  <%= f.check_box :tag_list, "landscape" %>
  <%= f.check_box :tag_list, "people" %>
<% end %>

You should change up your f.checkbox lines a bit:

<%= form_for(@photo) do |f| %>
  <%= f.label :tag_list %>
  <%= f.check_box :tag_list, { :multiple => true }, 'landscape', nil %>
  <%= f.check_box :tag_list, { :multiple => true }, 'people', nil %>
<% end %>

Which will post something like this when submitted (with only people selected, for example):

{ :post => { :tag_list => ['', 'people'] } }



回答2:


For anyone trying to get this to work with Rails 4 and strong parameters, I also had to permit the the tag_list param as an array.

params.require(:clip).permit(
  :name, :other_params, { tag_list: [] }
)


来源:https://stackoverflow.com/questions/7701183/rails3-acts-as-taggable-with-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!