Hi,
As part of implementing a Twitter clone I am trying to model a friendship
association using Sequel,
where two users are called friends if A follows B and B also follows A.
This is the code I came up with so far :
DB.create_table? :users do
String :nickname, :size => 20, :primary_key => true
String :email, :size => 255, :null => false
String :description, :size => 255, :null => false
end
DB.create_table? :relationships do
foreign_key :user_id, :users, :key => :nickname, :type => String,
:on_update => :cascade, :on_delete => :cascade
foreign_key :follower_id, :users, :key => :nickname, :type => String,
:on_update => :cascade, :on_delete => :cascade
primary_key [:user_id, :follower_id]
end
class User < Sequel::Model
many_to_many :followers,
:class => self, :join_table => :relationships,
:left_key => :user_id, :right_key => :follower_id
many_to_many :follows,
:class => self, :join_table => :relationships,
:right_key => :user_id, :left_key => :follower_id
# Friendship relation: A follows B and B follows A
many_to_many :friends
end
User.unrestrict_primary_key
user = User.find(:nickname => "me") || User.create(:nickname => "me")
p user.followers
# SELECT "users".* FROM "users"
# INNER JOIN "relationships"
# ON (("relationships"."follower_id" = "users"."nickname")
# AND ("relationships"."user_id" = 'me')) # why not use 'WHERE' here?
p user.follows
# SELECT "users".* FROM "users"
# INNER JOIN "relationships"
# ON (("relationships"."user_id" = "users"."nickname")
# AND ("relationships"."follower_id" = 'me'))
Here is a gist of all tables and
associations<https://gist.github.com/4110827>of this Twitter clone.
As I am quite new to both Sequel and relational databases, I would be glad
if someone could help me answer the following questions:
- Does the above code follow Sequel's 'best practices' or is there
something I could improve?
- How can I express the many_to_many :friends association in Sequel?
Stefan
--
You received this message because you are subscribed to the Google Groups
"sequel-talk" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/sequel-talk/-/bFllpTtgJcEJ.
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/sequel-talk?hl=en.