jam-cloud/ruby/lib/jam_ruby/models/friendship.rb

70 lines
2.0 KiB
Ruby
Raw Permalink Normal View History

2012-10-01 21:27:32 +00:00
module JamRuby
2012-10-14 04:21:52 +00:00
class Friendship < ActiveRecord::Base
2012-10-01 21:27:32 +00:00
2012-12-30 14:39:41 +00:00
attr_accessible :user_id, :friend_id
2012-10-14 04:21:52 +00:00
self.primary_key = 'id'
2012-10-01 21:27:32 +00:00
belongs_to :user, :class_name => "JamRuby::User", :foreign_key => "user_id", :inverse_of => :inverse_friendships
belongs_to :friend, :class_name => "JamRuby::User", :foreign_key => "friend_id", :inverse_of => :friendships
2012-10-01 21:27:32 +00:00
after_save :track_user_progression
2012-12-30 14:39:41 +00:00
def self.save(user_id, friend_id)
friendship = Friendship.where("user_id='#{user_id}' AND friend_id='#{friend_id}'")
2013-01-11 03:42:32 +00:00
if friendship.nil? || friendship.size == 0
2012-12-30 14:39:41 +00:00
Friendship.create(:user_id => user_id, :friend_id => friend_id)
Friendship.create(:user_id => friend_id, :friend_id => user_id)
end
end
2013-03-15 04:22:31 +00:00
# not like .save() in that it does not check for an existing friendship. The caller is responsible
# for checking for errors on the models
def self.save_using_models(user, friend)
this = Friendship.new
this.user = user
this.friend = friend
that = Friendship.new
that.user = friend
that.friend = user
this.save
that.save
return [this, that]
end
def self.search(query, user_id, options = { :limit => 10 })
# only issue search if at least 2 characters are specified
2013-06-22 23:35:42 +00:00
if query.nil? || query.length < 2 || user_id.nil?
return []
end
# create 'anded' statement
query = Search.create_tsquery(query)
if query.nil? || query.length == 0
return []
end
friends = Friendship.joins(
%Q{
INNER JOIN
users
ON friendships.friend_id = users.id
WHERE friendships.user_id = '#{user_id}'
AND users.name_tsv @@ to_tsquery('jamenglish', '#{query}')
}
)
friends = friends.limit(options[:limit])
return friends
end
def track_user_progression
self.user.update_progression_field(:first_friended_at)
end
2012-10-14 04:21:52 +00:00
end
2012-10-01 21:27:32 +00:00
end