【问题标题】:Strong parameters for different controller methods不同控制器方法的强参数
【发布时间】:2019-04-20 03:30:17
【问题描述】:

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

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

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

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

你如何为不同的控制器方法制定不同的需求强参数?

【问题讨论】:

    标签: ruby-on-rails strong-parameters


    【解决方案1】:

    您的“强参数方法”只是 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 只是一个脚手架约定。

    【讨论】:

      【解决方案2】:

      做一些类似的事情

      class FooController < ApplicationController
      
      
        def create
          @post = Post.new(create_params)
          if @post.save
            blah
          else
            blah
          end
        end
      
        def index
          ... something else
        end
      
      private
      
        def create_params 
          params.require(:post).permit(:body, :is_public, :title, :id)
        end
      
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-11-09
        • 2018-10-27
        • 2016-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多