首页 > 解决方案 > 不同控制器方法的强参数

问题描述

我正在 Rails 中创建一个控制器,我正在寻找方法为不同的控制器方法提供不同的强参数

在更新和新操作中,我想要求post

params.require(:post).permit(:body, :is_public, :title, :id)

但是在 中post/index,我不需要这些参数。

您如何为不同的控制器方法制作不同的强参数?

标签: ruby-on-railsstrong-parameters

解决方案


您的“强参数方法”只是 Ruby 方法。你可以有多少你想要的。

class PostsController < ApplicationController

  def create
    @post = Post.new(create_params)
  end

  def update
    @post = Post.find(params[:id])
    if @post.update(update_params)
      # ...
    else 
      # ...
    end
  end

  private

  def base_params
    params.require(:post)
  end
  
  # Don't take IDs from the user for assignment!
  def update_params
    base_params.permit(:body, :title)
  end

  def create_params
    base_params.permit(:body, :title, :foo, :bar)
  end
end

您也可以随意命名它们。调用它[resource_name]_params只是一个脚手架约定。


推荐阅读