Created
August 24, 2010 23:24
-
-
Save stympy/548539 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[ | |
{:name => 'Alice', :friend_list => '2,3' }, | |
{:name => 'Bob', :friend_list => '1' }, | |
{:name => 'Charlie', :friend_list => '2' } | |
].each do |u| | |
User.create(u) | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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