0

投稿 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 のタグは存在しますが、ID 200 のタグはありません。

何か案は?

4

1 に答える 1