Combine relation with different foreign keys


#1

I have a code like this

module Relations
  class Messages < ROM::Relation[:sql]
    schema(:messages, infer: true) do
      attribute :id, Types::Int
      attribute :sender_id, Types::ForeignKey(:users)
      attribute :recipient_id, Types::ForeignKey(:users)

      associations do
        belongs_to :users, as: :sender, combine_key: :sender_id
        belongs_to :users, as: :recipient, combine_key: :recipient_id
      end

      primary_key :id
    end
  end
end
module Relations
  class Users < ROM::Relation[:sql]
    schema(:users) do
      attribute :id, Types::Int
      attribute :login, Types::String

      associations do
        has_many :messages
      end

      primary_key :id
    end
  end
end

When I want to combine sender and recipient of a message

repo.messages.combine(:sender, :recipient).by_pk(message.id).one
=> #<ROM::Struct::Message id=37 sender_id=1 recipient_id=2 body="first message" opened=false sender=#<ROM::Struct::Sender id=1 login="bob"> recipient=#<ROM::Struct::Recipient id=1 login="bob">>

I want recipient to be a correct user record


#2

Try changing combine_key settings to foreign_key, because that’s what it needs in order to figure out how to fetch associated records. combine_key is used to merge data in memory, in most common scenarios they are the same as fks, but conceptually they are different.