更改作为参数接收的嵌套键的名称 [英] change the name of nested keys received as parameter

查看:54
本文介绍了更改作为参数接收的嵌套键的名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

rails 中的嵌套参数通过附加到键的属性进行传递,然后将其传递给 permit

Hi in rails the nested parameters are passed with attributes appended to the key's and then its is passed to permit

如果我收到正常的哈希值并想在调用 permit 之前将属性附加到每个嵌套键

If I receive normal hash and want to append attribute to each nested key before permit is called

怎么做?

"project":{  
  "project_name":"test",
  "tentative_start_date":"2018-12-12",
  "tentative_end_date":"2019-12-12",
"project_roles":[  
     {  
        "role_id":1,
        "project_role_skills":[  
           {  
              "skill":{  
                 "skill_type":"C++",
                 "id":2
              }
           }
        ],
        "project_role_users":[  

        ],
        "role_end_date":"2018-12-12",
        "role_start_date":"2018-12-12"
     }
  ]

}}

这是我收到的请求,我想将属性附加到 project_roles、project_role_skill 等,以便 rails 接受该请求

This is the request I received and I want to append attribute to project_roles,project_role_skill and so on so that rails accept that

请大家帮忙

推荐答案

TL;DR:

def params_with_deep_appended_nested_attributes(_params)
  modified_params = _params.clone

  _params.each do |k, v|
    if v.is_a?(Array)
      modified_params["#{k}_attributes"] = []

      v.each_with_index do |vv, index|
        if vv.is_a?(ActionController::Parameters)
          modified_params["#{k}_attributes"][index] = params_with_deep_appended_nested_attributes(vv)
        end
      end

      modified_params.delete(k)

    elsif v.is_a?(ActionController::Parameters)
      modified_params["#{k}_attributes"] = params_with_deep_appended_nested_attributes(v)
      modified_params.delete(k)
    end
  end

  modified_params
end

用法示例:

# rails console
example_json_hash_request = {
  "project": {
    "project_name":"test",
    "tentative_start_date":"2018-12-12",
    "tentative_end_date":"2019-12-12",
    "project_roles": [
       {  
          "role_id":1,
          "project_role_skills":[  
             {  
                "skill":{  
                   "skill_type":"C++",
                   "id":2
                }
             }
          ],
          "project_role_users":[  

          ],
          "role_end_date":"2018-12-12",
          "role_start_date":"2018-12-12"
       }
    ]
  }
}

# simulate `params` value in the controller
params = ActionController::Parameters.new(example_json_hash_request)

modified_params = params_with_deep_appended_nested_attributes(params)

pp modified_params.permit!.to_hash
# {"project_attributes"=>
#   {"project_name"=>"test",
#    "tentative_start_date"=>"2018-12-12",
#    "tentative_end_date"=>"2019-12-12",
#    "project_roles_attributes"=>
#     [{"role_id"=>1,
#       "role_end_date"=>"2018-12-12",
#       "role_start_date"=>"2018-12-12",
#       "project_role_skills_attributes"=>
#        [{"skill_attributes"=>{"skill_type"=>"C++", "id"=>2}}],
#       "project_role_users_attributes"=>[]}]}}

解决方案:

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  # ...
  # I added `= params` to default to the `params` value here in the controller
  def params_with_deep_appended_nested_attributes(_params = params)
    modified_params = _params.clone

    _params.each do |k, v|
      if v.is_a?(Array)
        modified_params["#{k}_attributes"] = []

        v.each_with_index do |vv, index|
          if vv.is_a?(ActionController::Parameters)
            modified_params["#{k}_attributes"][index] = params_with_deep_appended_nested_attributes(vv)
          end
        end

        modified_params.delete(k)

      elsif v.is_a?(ActionController::Parameters)
        modified_params["#{k}_attributes"] = params_with_deep_appended_nested_attributes(v)
        modified_params.delete(k)
      end
    end

    modified_params
  end
  # ...
end

# app/controllers/projects_controller.rb
class ProjectsController < ApplicationController
  def create
    @project = Project.new(project_params)

    if @project.save
      # ...
    else
      # ...
    end
  end

  def project_params
    params_with_deep_appended_nested_attributes.require(:project_attributes).permit(
      :project_name, :tentative_start_date, :tentative_end_date,
      project_roles_attributes: [
        :role_id, :role_end_date, :role_start_date,
        project_role_skills_attributes: [
          skill_attributes: [
            :skill_type, :id
          ]
        ],
        project_role_users_attributes: []
      ]
    )
  end
end

不要忘记在模型中定义嵌套属性":

Don't forget to define the "nested attributes" in the models:

# app/models/project.rb
class Project < ApplicationRecord
  has_many :project_roles
  accepts_nested_attributes_for :project_roles
end

# app/models/project_role.rb
class ProjectRole < ApplicationRecord
  belongs_to :project
  has_many :project_role_skills
  has_many :project_role_users
  accepts_nested_attributes_for :project_role_skills
  accepts_nested_attributes_for :project_role_users
end

# app/models/project_role_skill.rb
class ProjectRoleSkill < ApplicationRecord
  belongs_to :project_role
  belongs_to :skill
  accepts_nested_attributes_for :skill
end

待办事项:

  • 添加缓存 params_with_deep_appended_nested_attributes 返回值,以避免每次调用 params_with_deep_appended_nested_attributes 时都运行代码.
  • TODOs:

    • add cahing of the params_with_deep_appended_nested_attributes return value, to avoid running the code each time params_with_deep_appended_nested_attributes is going to be called.
    • 这个问题我很感兴趣.将来我可能会用到我的这段代码.

      这篇关于更改作为参数接收的嵌套键的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆