Relacja między dwoma tabelami

Witam,

mam tabele users, user_gifts, gifts

tabela user_gifts wygląda tak:

id | from_user_id | to_user_id | gift_id |

[code=“ruby”]class UserGift < ActiveRecord::Base
belongs_to :from_user, :class_name => ‘User’, :foreign_key => ‘from_user_id’
belongs_to :to_user, :class_name => ‘User’, :foreign_key => ‘to_user_id’
end

class User < ActiveRecord::Base
has_many :user_gifts
has_many :my_gifts,:through => :user_gifts,:source => :to_user
end[/code]
Przy zapytaniu pojawia się user_id a nie to_user_id

Oczywiście, że chce ‘user_id’, sam piszesz, że User ma wiele user_gifts i to wszystko co mówisz o tym połączeniu musisz pokazać mu :foreign_key, tylko nie wiadomo co to ma być za klucz ;-). Coś takiego będzie chyba lepsze:

[code]# Migracja
class CreateTables < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.timestamps
end

create_table :gifts do |t|
  t.timestamps
end

create_table :user_gifts do |t|
  t.belongs_to :from_user
  t.belongs_to :to_user
  t.belongs_to :gift
  t.timestamps
end

# indeksy na user_gifts

end

def self.down
drop_table :user_gifts
drop_table :gifts
drop_table :users
end
end

User

class User < ActiveRecord::Base
has_many :received_user_gifts, :class_name => ‘UserGift’, :foreign_key => ‘to_user_id’
has_many :gaved_user_gifts, :class_name => ‘UserGift’, :foreign_key => ‘from_user_id’

has_many :received_gifts, :through => :received_user_gifts, :source => :gift
has_many :gaved_gifts, :through => :gaved_user_gifts, :source => :gift
end

Gift

class Gift < ActiveRecord::Base
has_many :user_gifts
belongs_to :user, :through => :user_gifts, :source => :receiver
end

class UserGift < ActiveRecord::Base
belongs_to :receiver, :foreign_key => ‘to_user_id’
belongs_to :donor, :foreign_key => ‘from_user_id’
belongs_to :gift
end[/code]

ok, dzięki, działa