Reddirt
Reddirt

Reputation: 5953

Rails create in model - except attributes

I'm creating an :expense from a :recurringexpense

The :recurring expense has attributes that are not in :expense.

I thought this would work:

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

But, I'm getting this:

unknown attribute: frequency

Upvotes: 1

Views: 536

Answers (1)

Mori
Mori

Reputation: 27779

You just need to call except directly on the attributes hash:

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

As you note in your comment, you also need to make sure your keys in the except argument are the right type. You could also do this with

.attributes.symbolize_keys.except(...)

Upvotes: 2

Related Questions