form_for with has_many:through

时间:2012-07-21 03:28:43

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

所以我有一个简单的帖子模型has_many标签:通过post_tags。这允许多对多的关系。但是我无法使form_for和fields_for工作。我真的被困了,因为我找不到有关has_many:through关系的form_for助手的任何文档。我观看了轨道演员,阅读以前的堆栈问题,甚至研究了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

1 个答案:

答案 0 :(得分:3)

:tag_attributes

中将attr_accessible添加到Post
attr_accessible :title, ..., :tag_attributes, ...