【发布时间】:2020-05-06 21:16:28
【问题描述】:
我有一个表单,其中包含一些用户可以在帖子上选择的预置标签。这些标签设置有has_many through: 关系。一切似乎都正常,但是当我保存(帖子确实保存)时,控制器的保存方法中有一个Unpermitted parameter: :tags。
标签模型:
class Tag < ApplicationRecord
has_many :post_tags
has_many :posts, through: :post_tags
end
PostTag 模型:
class PostTag < ApplicationRecord
belongs_to :tag
belongs_to :post
end
后模型:
class Post < ApplicationRecord
...
has_many :post_tags
has_many :tags, through: :post_tags
后控制器方法:
def update
# saves tags
save_tags(@post, params[:post][:tags])
# updates params (not sure if this is required but I thought that updating the tags might be causing problems for the save.
params[:post][:tags] = @post.tags
if @post.update(post_params)
...
end
end
...
private
def post_params
params.require(:post).permit(:name, :notes, tags: [])
end
def save_tags(post, tags)
tags.each do |tag|
# tag.to_i, is because the form loads tags as just the tag id.
post.post_tags.build(tag: Tag.find_by(id: tag.to_i))
end
end
查看(标签是显示为按钮的复选框):
<%= form.label :tags %>
<div class="box">
<% @tags.each do |tag| %>
<div class="check-btn">
<label>
<%= check_box_tag('dinner[tags][]', tag.id) %><span> <%= tag.name %></span>
</label>
</div>
<% end %>
</div>
再次保存,并且工作正常,但我想摆脱控制台中抛出的Unpermitted parameter。
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-6