How about something like this:

class User < ActiveRecord::Base
   has_many :relations, :foreign_key => "from_user"
end

class Relation < ActiveRecord::Base
   belongs_to :from_user, :class_name => "User", :foreign_key => "from_user"
   belongs_to :to_user, :class_name => "User", :foreign_key => "to_user"
end


To print list of all friends of , say, first user ind DB, you can something
like this:

User.first.relations.all.each { |r| puts r.to_user.name }


Here is Migrations for two tables:

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end


class CreateRelations < ActiveRecord::Migration
  def self.up
    create_table :relations do |t|
      t.integer :from_user
      t.integer :to_user
      # other data specific to relation
      t.timestamps
    end
  end

  def self.down
    drop_table :relations
  end
end

*****
It may have some gotchas, but can be enhanced.



On Thu, Sep 16, 2010 at 11:17 PM, Marnen Laibow-Koser
<[email protected]>wrote:

> pipplo wrote:
> > I'm working on an app with a friend type system.  I currently have
> > setup like this with 2 tables.
> >
> > users table keeps track of users
> >
> > user_relationships table keeps track of friendships.  Now, there
> > should be two rows for each relationship.  This is to keep track of
> > the directional nature of the relationship between users. Each time a
> > relationship is made, both rows should be inserted into the table.
> >
> > user_1 user_2 data
> > user_2 user_1 data
> [...]
>
> That's not necessarily a great idea.  Please see
> http://www.ruby-forum.com/topic/213468 .
>
> Best,
> --
> Marnen Laibow-Koser
> http://www.marnen.org
> [email protected]
> --
> Posted via http://www.ruby-forum.com/.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Ruby on Rails: Talk" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected]<rubyonrails-talk%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/rubyonrails-talk?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to