2012-07-21 95 views
0

所以我有一个简单的post模型has_many标签:通过post_tags。这允许多对多的关系。不过,我一直无法获得form_for和fields_for的工作。我真的被卡住了,因为我无法通过has_many:through关系在form_for helper上找到任何文档。我观察了轨道投影,阅读了以前的堆栈问题,甚至在Rails 3 Way中进行了研究。任何人,这是我得到的。form_for with has_many:通过

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 

回答

3

添加:tag_attributesattr_accessiblePost

attr_accessible :title, ..., :tag_attributes, ... 
+0

哇真的...我可以发誓,左,右,我已经试过了。但给它一个镜头和繁荣,它的工作。有趣的后续问题。如果可以使用现有记录,我该如何告诉它...'如果Tag.find_by_name(params [:tag]'? – AdamCooper86 2012-07-21 18:38:26