接受'_attributes'后缀的嵌套Attribures

时间:2017-11-28 01:06:00

标签: ruby-on-rails activerecord

所以我正在做一个API而且我正在使用Has_many关联,因为我想在创建父亲时创建一个模型,所以我决定使用accepts_nested_attributes。 根据我的知识,如果我不使用“_attributes”后缀,它会引发一个错误:

  

的ActiveRecord :: AssociationTypeMismatch

在API中,我为后请求执行此操作:

{
    "content": {
        "name": "Teste",
        "schedulings_attributes":[
            {
                "days_attributes": [
                        {
                            "start": "2011-10-28",
                            "end": "2010-09-07"
                        },
                        {
                            "start": "2012-08-30",
                            "end": "2017-06-31"
                        }
                    ],
                    "hours_attributes": [
                        {
                            "start": "2000-01-01T01:51:30.000Z",
                            "end": "2000-01-01T15:03:11.000Z"
                        },
                        {
                            "start": "2000-01-01T02:23:39.000Z",
                            "end": "2000-01-01T00:37:51.000Z"
                        }
                    ],
                    "week_attributes": {
                        "monday": true,
                        "thursday": true,
                        "wednesday": true,
                        "tuesday": true,
                        "friday": true,
                        "saturday": true,
                        "sunday": true
                }
            }
        ]
    }
}

问题是,我不想要'_attributes'后缀。 有一种方法可以在不引发活动记录错误的情况下接受它吗?在控制器处进行一些处理?

1 个答案:

答案 0 :(得分:0)

我发现了一种治疗方法。

def scheduling_treatment(treated_params)
   treated_params[:schedulings].map do |attributes|
      attributes[:days_attributes] = attributes.delete(:days)
      attributes[:hours_attributes] = attributes.delete(:hours)
      attributes[:week_attributes] = attributes.delete(:week)
   end
   treated_params
end

在上面的方法中,我收到了关键的调度,并对其进行了映射我抓住了密钥并删除了旧密钥,并使用后缀' _attributes'将其交换为新密钥。 控制器内部:

def content_params
   new_params = params.require(:content).permit(:id, :name, schedulings: [
        days: [:start, :end],
        hours: [:start, :end],
        week: [:monday, :thursday, :wednesday, :tuesday, :friday, :saturday, :sunday]])
        new_params = scheduling_treatment(new_params)
        new_params[:schedulings_attributes] = new_params.delete(:schedulings)
        new_params.permit!
end
相关问题