Skip to content

Instantly share code, notes, and snippets.

@stympy
Created August 24, 2010 23:24
Show Gist options
  • Save stympy/548539 to your computer and use it in GitHub Desktop.
Save stympy/548539 to your computer and use it in GitHub Desktop.
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
[
{:name => 'Alice', :friend_list => '2,3' },
{:name => 'Bob', :friend_list => '1' },
{:name => 'Charlie', :friend_list => '2' }
].each do |u|
User.create(u)
end
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment