验证多对多关联

时间:2013-04-22 18:25:44

标签: ruby-on-rails ruby-on-rails-3 many-to-many

帖子1 - * post_tags * - 1个标签

帖子有很多标签,标签有很多帖子。它们通过post_tags表相关联。

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

标签表是一个目录,我只希望用户为帖子选择合适的标签。 所以在我看来,我有一个多选:

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

这有效,但问题是当我发送无效ID时出现此错误

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

ID为1的标签存在但标识为200的标签不存在。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

遇到问题,当您发送一些无效的tag_id时,200,Rails将首先搜索ID为200的Tag是否确实存在。因此,解决此问题的最佳方法是使用前置过滤器,以确保获得正确或有效的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

这可以解决你的问题,希望你这次不会得到例外......