【问题标题】:form_for with has_many :throughform_for 和 has_many :通过
【发布时间】:2012-07-21 03:28:42
【问题描述】:

所以我有一个简单的帖子模型,它有多个标签:通过 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

【问题讨论】:

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


    【解决方案1】:

    Post 中添加:tag_attributesattr_accessible

    attr_accessible :title, ..., :tag_attributes, ...
    

    【讨论】:

    • 哇真的...我可以左右发誓我已经尝试过了。但是给了它一个机会和繁荣,它奏效了。有趣的后续问题。如果现有记录可用,我如何告诉它使用现有记录...if Tag.find_by_name(params[:tag]
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多