Skip to content

Instantly share code, notes, and snippets.

@stympy
Created August 24, 2010 23:24
Show Gist options
  • Select an option

  • Save stympy/548539 to your computer and use it in GitHub Desktop.

Select an option

Save stympy/548539 to your computer and use it in GitHub Desktop.

Revisions

  1. stympy created this gist Aug 24, 2010.
    10 changes: 10 additions & 0 deletions schema.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    ActiveRecord::Schema.define(:version => 20100824224246) do

    create_table "users", :force => true do |t|
    t.string "name"
    t.text "friend_list"
    t.datetime "created_at"
    t.datetime "updated_at"
    end

    end
    7 changes: 7 additions & 0 deletions seeds.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    [
    {:name => 'Alice', :friend_list => '2,3' },
    {:name => 'Bob', :friend_list => '1' },
    {:name => 'Charlie', :friend_list => '2' }
    ].each do |u|
    User.create(u)
    end
    19 changes: 19 additions & 0 deletions user.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    class User < ActiveRecord::Base
    attr_protected :friend_list

    def following
    self.class.all(:conditions => "id in (#{friend_list})")
    end

    def follow(id)
    update_attribute(:friend_list, (friend_list.split(',').map(&:to_i) | [id.to_i]).join(','))
    end

    def unfollow(id)
    update_attribute(:friend_list, (friend_list.split(',').map(&:to_i) - [id.to_i]).join(','))
    end

    def followers
    self.class.all(:conditions => ['find_in_set(?, friend_list)', id])
    end
    end