我有模型LoanPlan
和Career
,它们由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
答案 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