0

posts 1--* post_tags *--1 tags

A post has many tags and a tag has many posts. They are related through the post_tags table.

post.rb
class Post < ActiveRecord::Base
  attr_accressible :tag_ids

  has_many :post_tags
  has_many :tags, :through => :post_tags
end

tag.rb
class Tag < ActiveRecord::Base
  has_many :post_tags
  has_many :posts, :through => :post_tags
end

post_tag.rb
class PostTag < ActiveRecord::Base
  belongs_to :post
  belongs_To :tag
end

posts_controller.rb
class PostsController < ApplicationController
  def new
    @post = Post.new
  end

  def create
    @post = Post.new(params[:post])
    @post.save ? redirect_to(:action => 'index') : render(:action => 'new')
  end
end

The tags table is a catalog and I just want the user to select the appropriate ones for the post. So in my view I have a multiple select:

new.html.erb
post_form.collection_select(:tag_ids, @tags, nil, nil, {}, { :multiple => true })

This works but the problem is when I send invalid ids I get this error

ActiveRecord::RecordNotFound in Posts#create
Couldn't find all Tags with IDs (1, 200) (found 1 results, but was looking for 2)

Tag with id 1 exists but tag with id 200 doesn't.

Any ideas?

4

1 回答 1

0

有你的问题,当你发送一些无效的 tag_id 比如说 200 时,Rails 将首先搜索 ID 为 200 的标签是否真的存在。因此,解决此问题的最佳方法是使用 before 过滤器,以确保您获得正确或有效的 id。然后你可以简单地做一个任务,将 tag_ids 分配给帖子......你可以做这样的事情

before_filter :find_tags_from_ids

def find_tags_from_ids
  @tags = Tag.where(:id => params[:post][:tag_ids]
end

def create
  @post = Post.new(params[:post])
  @post.tags << @tags
  @post.save ? redirect_to(:action => 'index') : render(:action => 'new')
end

这将解决您的问题,希望您这次不会遇到异常。

于 2013-04-22T20:05:17.967 回答