0

I am trying to generate a tagging system similar to SO. I am using the Select2 gem. When the user initially goes to the new page the form should only display their tags. When on the page they can create new tags by typing out tag names and separating them by spaces or commas.

My issues is that when I go to submit this form, the tags are not properly linking to an ID. I get the error "Couldn't find Tag with id = 0" or if I have the number 12 as the tag, "Couldn't find Tag with id = 12"

A user has_many tags; a post has many taggings; a post has many tags through taggings; a tag has many taggings; a tag has many posts through taggings; a tag belongs to an user

How could I specify the tag id name and only have the tag name show up?

My Tags Controller looks like this

  respond_to :json
  def index
    @tags = current_user.tags
    respond_with(@tags.map{|tag| {:id => tag.id, :name => tag.name, :user_id => tag.user_id} })
  end

My JavaScript looks like this

var items = [];
$.getJSON('http://localhost:3000/tags.json', function(data) {
        $.each(data, function(i, obj) {
             return items.push(obj.name);
        });
   $("#post_tag_ids").select2({
        tags: items,
        tokenSeparators: [",", " "]
        });
   });

My form looks like this

= semantic_form_for([@user, @post], :html => { :class => 'form-horizontal' }) do |f|
  = f.inputs do
    = f.input :summary, :label => false, :placeholder => "Title"
    = f.input :tag_ids, :as => :string, :label => false, :placeholder => "Tags", input_html: {:id => "post_tag_ids", :cols => 71}
  = f.buttons do
    .action
  = f.commit_button :button_html => { :class => "btn btn-primary" }

My Post Controller looks a little like this

def create
 @post = Post.new(params[:post])
 @post.user = current_user
 @post.save
 @post.tag!(params[:tag_ids], current_user.id)
end

My Post Model has a tag! method

def tag!(tags, user)
  tags = tags.split(",").map do |tag|
    Tag.find_or_create_by_name_and_user_id(tag, user)
  end
self.tags << tags
end
4

1 に答える 1

0

これを解決する秘訣は、モデルにセッターメソッドを設定することでした。私は最終的にこのようなものを使用しました:

  def tag_ids=(tags_string)
    self.taggings.destroy_all
    tag_names = tags_string.split(",").collect{|s| s.strip.downcase}.uniq
    tag_names.each do |tag_name|
      tag = Tag.find_or_create_by_name_and_user_id(tag_name, self.user.id)
      tagging = self.taggings.new
      tagging.tag_id = tag.id
    end
 end

そして、コントローラーで、ユーザーキーをフォームparamsハッシュにマージする必要がありました。

于 2012-11-08T04:17:51.733 に答える