So I have a simple post model that has_many tags :through post_tags. This allows for a many to many relationship. However I haven’t been able to get the form_for and fields_for to work. I am really stuck because I can’t find any documentation on the form_for helper with a has_many :through relationship. I watched the rails cast, read previous stack questions, and even researched in the Rails 3 Way. Anywho, here’s what I got.
class Post < ActiveRecord::Base
belongs_to :blog
has_many :post_tags, :dependent => :destroy
has_many :tag, :through => :post_tags, :dependent => :destroy
has_many :post_categories, :dependent => :destroy
has_many :category, :through => :post_categories, :dependent => :destroy
attr_accessible(:title, ...)
accepts_nested_attributes_for :tag, :allow_destroy => true
end
and
class PostTag < ActiveRecord::Base
belongs_to :tag
belongs_to :post
end
and
class Tag < ActiveRecord::Base
has_many :post_tags
has_many :post, :through => :post_tags
end
and my controller code is
def new
@title = "Create a New Post"
@user = User.find(params[:user_id])
@blog = @user.blog
@post = @blog.post.new
@post.ptype = params[:type]
3.times { @post.tag.build}
end
def create
@user = User.find(params[:user_id])
@blog = @user.blog
@post = @blog.post.new(params[:post])
if @post.save
...
end
end
and the form is
<%= form_for([@user,@blog,@post],:url => user_blogs_posts_path, :html => {:multipart=>true}) do |p| %>
<%= render 'shared/error_messages', :object => p.object %>
...
<%= p.fields_for :tag do |t|%>
<%=t.label :tag %>
<%=t.text_field :tag %>
<% end %>
<%=p.submit%>
<% end %>
and the error is
Can't mass-assign protected attributes: tag_attributes
Add
:tag_attributestoattr_accessibleinPost