【问题标题】:Chaining strong parameters in Rails controller在 Rails 控制器中链接强参数
【发布时间】:2015-12-12 23:47:03
【问题描述】:

在这个 Rails 控制器中,我有一个 create 和一个 update 方法共享一些参数,但我只希望 course_id 在创建时可设置。我怎样才能“干”这两种方法?有没有办法将两个permits 链接起来,这样我就可以说“许可描述和标题”,然后在 create 方法中将“course_id”添加到许可中?

def topic_create_params
  params.require(:topic).permit(
    :course_id,
    :description,
    :title
  )
end

def topic_update_params
  params.require(:topic).permit(
    :description,
    :title
  )
end

【问题讨论】:

    标签: ruby-on-rails strong-parameters


    【解决方案1】:

    我认为这可行:

    def topic_params(attrs = [])
      params.require(:topic).permit *([:description, :title] + attrs)
    end
    
    def topic_create_params
      topic_params([:course_id])
    end
    

    【讨论】:

      【解决方案2】:

      最终得到的结果与@Hoang Phan 的答案略有不同,而是在方法参数中使用 splat 运算符...

      def topic_params(*attrs)
        attrs = ([:description, :title] + attrs).uniq
        params.require(:topic).permit(attrs)
      end
      
      def topic_create_params
        topic_params(:course_id, :thing_id)
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多