如何在没有ActiveModel的情况下更新从视图发送的哈希:: ForbiddenAttributesError

时间:2015-10-11 08:24:34

标签: ruby-on-rails ruby-on-rails-4 params

使用Rails 4.我有一个用户提交更新名为Flow的对象。我在Flows和Locations之间有一个Rich Many-To_many关联。流可以有很多位置,但是当他们这样做时,我需要跟踪位置是源还是目的地。

为此,我有一个表单要求用户选择源位置,然后选择目标位置。在我的控制器中,我将具有适当附加属性的正确位置保存到连接表中。

然后我从prams散列中删除位置并将其余的参数提交给@ flow.update。

当我这样做时,我收到一个错误: ActiveModel :: ForbiddenAttributesError

我不明白为什么会这样,所有必填字段都列在我的params.permit中。 好像Rails根本不会让我触摸从视图中返回的哈希值,或者它变得被禁止。我该如何解决这个问题?有什么建议吗?

Flows_controller.rb

  def update
    @flow_id = params['id']
    @flow = Flow.find(@flow_id)
    old_flow_locs = @flow.flow_locations

    @source_loc_ids = params['flow']['source_location_ids']
    @source_loc_ids.reject!(&:empty?)
    @source_loc_ids.uniq!
    @source_loc_ids.each do |src_loc_id|

    flow_loc = FlowLocation.new()
    flow_loc.source = 'TRUE'
    flow_loc.flow_id = @flow_id
    flow_loc.location_id = src_loc_id
    flow_loc.save!
end

@dest_loc_ids = params['flow']['destination_location_ids']
@dest_loc_ids.reject!(&:empty?)
@dest_loc_ids.uniq!
@dest_loc_ids.each do |dst_loc_id|
  flow_loc = FlowLocation.new()
  flow_loc.destination = 'TRUE'
  flow_loc.flow_id = @flow_id
  flow_loc.location_id = dst_loc_id
  flow_loc.save!
end

# delete old flow locations
old_flow_locs.each do |x|
  x.destroy
end

@updated_flow_params = params['flow'].except('source_location_ids').except('destination_location_ids')



respond_to do |format|
  if @flow.update(@updated_flow_params)
    format.html { redirect_to @flow, notice: 'Flow was successfully updated.' }
    format.json { render :show, status: :ok, location: @flow }
  else
    format.html { render :edit }
    format.json { render json: @flow.errors, status: :unprocessable_entity }
  end
end

def flow_params
  params.require(:flow).permit(:title, :description, :source_id, :company_id, :service_id, :destination_id, :status, :source_location_ids, :destination_location_ids, :status_details)
end

从我的观点出来的Params看起来像这样:

{
"utf8": "✓",
"authenticity_token": "mkHsRahEh4Y7sUsEW+WgEYEWaM37WY7w4jkZbnRTZV6y6T7WWe2/s+oQYxvpRkx8GEqSxNxcLw9ZpKoT5s7AwQ==",
"flow": {
    "title": "Direct Transfer Intuitive to DASH Cloud",
    "company_id": "1",
    "service_ids": [
        "",
        "4"
    ],
    "source_location_ids": [
        "",
        "3"
    ],
    "destination_location_ids": [
        "",
        "2",
        "1"
    ]
},
"commit": "Update Flow",
"id": "16"
}

1 个答案:

答案 0 :(得分:1)

您必须在参数中允许数组,如下所示:

source_location_ids: []

所以在你的情况下你可以尝试:

def flow_params
  params.require(:flow).permit(:title, :description, :source_id, :company_id, :destination_id, :status, :status_details, source_location_ids: [], destination_location_ids: [], :service_ids: [])
end

此外,您只允许service_id而params散列显示service_ids数组。