Dukra
Dukra

Reputation: 47

Rails: assign_attributes fails because of a duplicated attribute name

I have an Order model related to the database table orders which has the column pay_type:integer, but later on a pay_types table was added and the Order model was modified to look like this:

class Order < ApplicationRecord
  belongs_to :pay_type
  ...
end

which means that now the Order model has 2 attributes with the name pay_type. I can still read the one related to the table column by using the read_attribute method:

order = Order.first
order.pay_type # nil
order.read_attribute(:pay_type) # 1

But when I try to assign to the latter by using the assign_attributes method like this:

order.assign_attributes(pay_type: 2)

I get the following error:

ActiveRecord::AssociationTypeMismatch (PayType(#14340) expected, got 2 which is an instance of Integer(#5000))

I know I could just change the name of the pay_type attribute on the Order model like this:

belongs_to pay_type_something, class_name: :PayType

and the repetition would be gone, but I just want to know: is there any way to assign a value to my first pay_type attribute without changing any names?

Upvotes: 1

Views: 220

Answers (1)

spickermann
spickermann

Reputation: 107077

You could try []= or write_attribute.

order[:pay_type] = 2 # or
order.write_attribute(:pay_type, 2)

But those methods are protected what limits their use cases. As you already notice best would be to rename the attribute or the association.

Upvotes: 3

Related Questions