使用不规则参数更新has_many属性

时间:2016-04-28 03:30:47

标签: ruby-on-rails

我有模型LoanPlanCareer,它们由join_table关联

来自另一个前端开发人员的请求参数将是这样的

 "loan_plan" => {
                  "id" => 32,
             "careers" => [
        [0] {
                     "id" => 8,
        },
        [1] {
                     "id" => 9,
        }
    ]
},

但是,我在ActiveRecord::AssociationTypeMismatch: Career(#70198754219580) expected, got ActionController::Parameters(#70198701106200)方法

中获得了update
def update
  @loan_plan.update(loan_plan_params)
end

当我尝试使用职业参数更新loan_plan模型时,它期望参数[“职业”]应该是careers object of a array而不是数组的ID。

所以我的工作是手动fectch数组的职业对象,并替换已消毒的参数。

看起来很脏,闻起来很糟糕,Rails方式有什么更好的解决方案吗?感谢

def loan_plan_params
  # params.fetch(:loan_plan, {})
  cleaned_params = params.require(:loan_plan).permit(
    :id, 
    :name, 
    {:careers=>:id}
  )
  cleaned_params["careers"] = Career.find(cleaned_params["careers"].map{|t| t["id"]})
  cleaned_params
end

模型

class LoanPlan < ActiveRecord::Base
  has_and_belongs_to_many :careers
  accepts_nested_attributes_for :careers
end

1 个答案:

答案 0 :(得分:0)

在Rails方式中,params应为

"loan_plan" => {
  "id" => "32",
  "career_ids" => ["8", "9"]
}

且强参数loan_plan_params应为

def loan_plan_params
  params.require(:loan_plan).permit(
    :id,
    :name,
    :career_ids => []
  )
end