Pregunta

So, I have a user model:

class User < ActiveRecord::Base
    has_one :partner, class_name: "User", foreign_key: :id
    belongs_to :inverse_partner, class_name: "User", foreign_key: :id
end

And each user has an id (prepared by the scaffold), a partner_id and a inverse_partner_id column in the users table.

However, when I try to to do this:

aka[x].partner = shiro[x]

Where both aka[x] and shiro[x] are Users, I get this weird error where the SQL statement indicates that I'm setting id and not partner_id as I intended to:

SQLite3::MismatchException: datatype mismatch: UPDATE "users" SET "id" = ?, "updated_at" = ? WHERE "users"."id" = 4

I'm obviously doing something very wrong. Help?

¿Fue útil?

Solución

The only required change I see is in your associations' foreign_key option.

With the current setup you are basically using one single column for three different purposes i.e. primary key for users table, foreign key for partner association and foreign key for inverse_partner association. So, when this is done and you try to set partner such errors can be expected.

Set appropriate foreign keys for each relations as follows:

class User < ActiveRecord::Base
    has_one :partner, class_name: "User", foreign_key: :partner_id
    belongs_to :inverse_partner, class_name: "User", foreign_key: :inverse_partner_id
end
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top