socialforge/app/models/watchers_of_user.rb

67 lines
2.0 KiB
Ruby
Raw Normal View History

2013-08-22 16:42:13 +08:00
# fq
class WatchersOfUser < ActiveRecord::Base
attr_accessible :user_id, :watcher_id
belongs_to :user
validates_uniqueness_of :watcher_id, :scope => :user_id
validate :validate_user
validate :validate_watcher
validates_presence_of :watcher_id, :user_id
def self.watch_user(watcher_id, user_id)
unless user_id == watcher_id
@watchers_of_user = WatchersOfUser.new
@watchers_of_user.watcher_id = watcher_id
@watchers_of_user.user_id = user_id
@watchers_of_user.save
true
else
false
end
end
def cancel_watching_user
self.class.cancel_watching_user(self.watcher_id, self.user_id)
end
def self.cancel_watching_user(watcher_id, user_id)
self.delete_all(["user_id = ? and watcher_id = ?", user_id, watcher_id])
true
end
def self.find_users(watcher_id)
@user = WatchersOfUser.find_by_sql("select * from users where id in (select user_id from #{WatchersOfUser.table_name} where watcher_id = #{watcher_id})")
@user
# @watch_table_for_user=WatchersOfUser.where(:watcher_id => watcher_id)
# @user = []
# @watch_table_for_user.each do |watch|
# @user.push(watch.user)
# end
# @user
end
def self.find_watchers(user_id)
@watcher = WatchersOfUser.find_by_sql("select * from users where id in (select watcher_id from #{WatchersOfUser.table_name} where user_id = #{user_id})")
@watcher
# user = User.find(user_id)
# @watch_table_for_watcher = user.watchers_of_users
# @watcher = []
# @watch_table_for_watcher.each do |watch|
# user_temp = User.find(watch.watcher_id)
# @watcher.push(user_temp)
# end
# @watcher
end
#验证user是否存在
def validate_user
errors.add :user_id, :invalid if user.nil? || !user.active?
end
#验证watcher是否存在
def validate_watcher
user = User.where("id = ?", watcher_id).to_a.first
errors.add :watcher_id, :invalid if user.nil? || !user.active?
end
end