我有一个简单的博客应用,我希望能够创建一个帖子,并使用嵌套表单以相同的形式为它创建一个新的标签。
帖子和标签通过连接表具有多对多关系:
class PostTag < ActiveRecord::Base
belongs_to :post
belongs_to :tag
end
这是标签模型:
class Tag < ActiveRecord::Base
has_many :post_tags
has_many :posts, :through => :post_tags
validates_presence_of :name
validates_uniqueness_of :name
end
Post model接受标签的嵌套属性:
class Post < ActiveRecord::Base
has_many :post_tags
has_many :tags, :through => :post_tags
accepts_nested_attributes_for :tags
validates_presence_of :name, :content
end
在posts控制器上,我允许tags_attributes:
def post_params
params.require(:post).permit(:name, :content, :tag_ids => [], :tags_attributes => [:id, :name])
end
在我的新帖子的表单中,我希望能够关联已有的标签(通过复选框)或使用fields_for通过嵌套表单创建新标签:
....
<div class="field">
<%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %><br>
<%= f.fields_for [@post, Tag.new] do |tag_form| %>
<p>Add a new tag:</p><br>
<%= tag_form.label :name %>
<%= tag_form.text_field :name %>
<% end %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我的错误是&#34;未经许可的参数:标记&#34;:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"dZnCgFxrvuoY4bIUMMxI7kTLEr/R32pUX55wwHZsS4Q=", "post"=>{"name"=>"post title", "content"=>"post content", "tag_ids"=>[""], "tag"=>{"name"=>"new tag"}}, "commit"=>"Create Post"}
Unpermitted parameters: tag
答案 0 :(得分:4)
变化:
<%= f.fields_for [@post, Tag.new] do |tag_form| %>
到
<%= f.fields_for(:tags, Tag.new) do |tag_form| %>