Rails在模型中创建 - 属性除外

时间:2014-01-24 17:12:15

标签: ruby-on-rails

我正在从:expense

创建:recurringexpense

:recurring expense的属性不在:expense

我认为这样可行:

def copy_to_expense
  @recurringexpense = Recurringexpense.find(params[:id]) # find original recurring expense
  @expense = Expense.create(@recurringexpense.attributes).except(:frequency, :last_date)

  redirect_to @recurringexpenses, notice: 'Expense was successfully created.'
end

但是,我得到了这个:

unknown attribute: frequency

1 个答案:

答案 0 :(得分:2)

您只需要直接在属性哈希上调用except

@expense = Expense.create(@recurringexpense.attributes.except(:frequency, :last_date))

正如您在评论中所述,您还需要确保except参数中的键是正确的类型。您也可以使用

执行此操作
.attributes.symbolize_keys.except(...)