Gozup
Gozup

Reputation: 1003

Rails polymorphic table that has other kinds of associations

I'm currently modeling a Rails 3.2 app and I need a polymorphic association named "archivable" in a table named "archives". No worries with it, but my "archives" table must also belongs_to a "connections" table. I just want to know if there's any constraints from Rails to do that.

You can see the model here

Another detail, my Connection model has twice user_id as foreign key. A user_id as sender and a user_is as receiver. Possible? I think what I did below won't work...

Here are my models associations.

class User < ActiveRecord::Base
  has_many :connections, :foreign_key => :sender
  has_many :connections, :foreign_key => :receiver
end

class Connections < ActiveRecord::Base
  belongs_to :user
  has_many :archives
end

class Archive < ActiveRecord::Base
  belongs_to :connection
  belongs_to :archivable, :polymorphic => true
end

class Wink < ActiveRecord::Base
  has_many :archives, :as => :archivable
end

class Game < ActiveRecord::Base
  has_many :archives, :as => :archivable
end

class Message < ActiveRecord::Base
  has_many :archives, :as => :archivable
end

Do you see anything wrong or something not doable with Rails?

Thank you guys.

Upvotes: 0

Views: 184

Answers (1)

pierallard
pierallard

Reputation: 3371

I think you want to do this :

class Connections
  belongs_to :sender, :class_name => 'User', :foreign_key => 'sender_id'
  belongs_to :receiver, :class_name => 'User', :foreign_key => 'receiver_id' 
end

class User
  has_many :sended_connections, :class_name => 'Connection', :as => :sender
  has_many :received_connections, :class_name => 'Connection', :as => :receiver
end

Important : Don't declare 2 times has_many :connections with the same name !

Upvotes: 1

Related Questions