我有一个简单的博客应用程序,我希望能够在其中创建一个帖子,并使用嵌套表单以相同的形式为其创建一个新标签。
Post 和 Tag 通过连接表具有多对多关系:
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 模型接受标签的嵌套属性:
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
在帖子 Controller 上,我允许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 %>
我的错误是“不允许的参数:标记”:
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
最佳答案
更改:
<%= f.fields_for [@post, Tag.new] do |tag_form| %>
至
<%= f.fields_for(:tags, Tag.new) do |tag_form| %>
关于ruby - 嵌套形式多对多关系不允许的参数 Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24003064/