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?