Forum: Ruby on Rails Multiple user_id columns

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
66c680f88e8c379fe408d32299dfb4e6?d=identicon&s=25 jjones (Guest)
on 2005-11-21 10:48
(Received via mailing list)
I have a table called 'users'.  I have a second table called 'comments'.
The comments table is in need of _two_ columns that both reference
different user ids within the 'users' table (one column for the user id
that originated the post, another column for the user id for which the
message is intended for.

Obviously I can't create two columns named 'user_id'. How do I go about
creating two columns that reference the same foreign column?

TIA.

Jim
Afcbb04db765e2506ab02d23850d55b8?d=identicon&s=25 dom (Guest)
on 2005-11-21 11:09
(Received via mailing list)
Jim Jones wrote:
> I have a table called 'users'.  I have a second table called 'comments'.
> The comments table is in need of _two_ columns that both reference
> different user ids within the 'users' table (one column for the user id
> that originated the post, another column for the user id for which the
> message is intended for.
>
> Obviously I can't create two columns named 'user_id'. How do I go about
> creating two columns that reference the same foreign column?

class User < ActiveRecord::Base
  has_many :sent_comments, :class_name => 'Comment', :conditions =>
"sender_user_id = #{self.id}"
  has_many :received_comments, :class_name => 'Comment', :conditions =>
"recipient_user_id = #{self.id}"
end

class Comment < ActiveRecord::Base
  belongs_to :sender, :class_name => 'User', :foreign_key =>
'sender_user_id'
  belongs_to :recipient, :class => 'User', :foreign_key =>
'recipient_user_id'
end

---

c = Comment.find_by_id N
...
puts c.sender.name
...
s = c.sender
c_of_s = s.sent_comments
...
c_of_s.each do |comment|
 ...
end
05d703f649ef1d07e78d7b479fb4c4ac?d=identicon&s=25 james.adam (Guest)
on 2005-11-21 12:01
(Received via mailing list)
class Comment < ActiveRecord::Base

  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  belongs_to :recipient, :class_name => 'User', :foreign_key =>
'recipient_id'

end

... by making the class and the FK explicit, you can name things
whatever you like..


- james
This topic is locked and can not be replied to.