51 lines
1.3 KiB
Ruby
51 lines
1.3 KiB
Ruby
class MessagesForUser < ActiveRecord::Base
|
|
attr_accessible :message, :messager_id, :user_id
|
|
belongs_to :user
|
|
|
|
MESSAGE_LENGTH_LIMIT = 60
|
|
|
|
validate :validate_user
|
|
validate :validate_messager
|
|
validates_presence_of :messager_id, :user_id, :message
|
|
validates_length_of :message, :maximum => MESSAGE_LENGTH_LIMIT
|
|
|
|
def self.leave_message(messager_id, user_id, message)
|
|
unless messager_id == user_id
|
|
@messages_for_user = self.new
|
|
@messages_for_user.messager_id = messager_id
|
|
@messages_for_user.user_id = user_id
|
|
@messages_for_user.message = message
|
|
@messages_for_user.save
|
|
true
|
|
else
|
|
false
|
|
end
|
|
end
|
|
|
|
def self.find_message(user_id)
|
|
user = User.find(user_id)
|
|
@message_table_for_user = user.messages_for_users.to_a
|
|
@message_table_for_user
|
|
end
|
|
|
|
def find_messager
|
|
@messager = User.where(:id =>messager_id)
|
|
@messager
|
|
end
|
|
|
|
def self.delete_message(message_id)
|
|
MessagesForUser.delete_all "id = #{message_id}"
|
|
end
|
|
|
|
#验证user是否存在
|
|
def validate_user
|
|
errors.add :user_id, :invalid if user.nil? || !user.active?
|
|
end
|
|
|
|
#验证messager是否存在
|
|
def validate_messager
|
|
user = User.where("id = ?", messager_id).to_a.first
|
|
errors.add :messager_id, :invalid if user.nil? || !user.active?
|
|
end
|
|
end
|