Morad Edwar Morad Edwar - 3 years ago 104
MySQL Question

Activeadmin form with a custom foreign key column name

I have two models

Person
and
Car
and I can't change the DB schema which has a foreign key column called
car
not
car_id
in the
Persons
table.

Till now it's ok because I used the following line in the
Person
model :

belongs_to :car, class_name: 'Car', foreign_key: 'car'


And now for example if I tried
Person.last.car
it returns a
Car
object based on the
Car ID
in this column.

But the problem is with
Activeadmin
because if the user tried to edit a
Person
record it suppose to load the current
Car
and select it by default on the list but it doesn't.

My Form code :

form do |f|
f.inputs 'Person Details' do
....
....
f.input :car
....
....
end
end


And also if I selected any car and clicked submit, I am facing this error
Car(#97670400) expected, got String(#19439720)


Also I tried to make an alias for the column but with no luck

alias_attribute :ca_id, :car


I am using
Rails 5.0.2
and the latest
ActiveAdmin
.

Answer Source

Car(#97670400) expected, got String(#19439720)

As I said, the straight forward and simple answer would be changing the column name to car_id(which is recommended) and using it in the form like f.input :car_id but as you insisted try providing a different(but meaningful) name to the association. Something like below

belongs_to :person_car, class_name: 'Car', foreign_key: 'car'

Explanation:

  • Naming Conflicts

You should avoid naming conflicts. The car(column name) in f.input :car conflicts with the association name car in belongs_to :car, class_name: 'Car', foreign_key: 'car' That is the reason for the error

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download