【问题标题】:Rails Unpermitted ParameterRails 不允许的参数
【发布时间】: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


    【解决方案1】:

    您的整个解决方案很有创意,但极其多余。而是使用集合助手:

    <%= form_with(model: @post) |f| %> 
      <%= f.collection_check_boxes :tag_ids, Tag.all, :id, :name %>
    <% end %>
    

    tags_ids= 是由has_many :tags, through: :post_tags 创建的特殊设置器(它们是为所有 has_many 和 HABTM 关联创建的)。它需要一个 id 数组,并会自动为您创建/删除连接行。

    您只需在控制器中将post[tag_ids] 列入白名单即可:

    class PostsController < ApplicationController
      # ...
    
      def create
        @post = Post.new(post_params)
        if @post.save 
          redirect_to @post 
        else
          render :new
        end
      end
    
      def update
        if @post.update(post_params)
          redirect_to @post 
        else
          render :edit
        end
      end
    
      private 
      # ...
    
      def post_params
        params.require(:post)
              .permit(:name, :notes, tag_ids: [])
      end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-14
      • 2013-08-01
      • 2023-03-23
      • 2013-07-25
      • 1970-01-01
      • 2019-09-17
      • 2017-02-01
      相关资源
      最近更新 更多