所以我有一个简单的帖子模型,它有多个标签:通过 post_tags。这允许多对多关系。但是我无法让 form_for 和 fields_for 工作。我真的被困住了,因为我在 form_for 助手上找不到任何文档,其中包含 has_many :through 关系。我观看了 rails 的施法,阅读了之前的堆栈问题,甚至研究了 Rails 3 Way。任何人,这就是我得到的。
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
和
class PostTag < ActiveRecord::Base
belongs_to :tag
belongs_to :post
end
和
class Tag < ActiveRecord::Base
has_many :post_tags
has_many :post, :through => :post_tags
end
我的控制器代码是
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
形式是
<%= 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 %>
错误是
Can't mass-assign protected attributes: tag_attributes