所以我有一个服务对象,它将投票和投票的用户提交到数据库中:
这是帖子模型:
class Post < ActiveRecord::Base
attr_accessible :comment_count, :downvote, :id, :text, :title, :upvote, :url, :user_id, :users_voted_up_by, :users_voted_down_by
serialize :users_voted_up_by, Array
serialize :users_voted_down_by, Array
belongs_to :user
end
这是用户模型:
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :username, :good_karma, :bad_karma, :posts_voted_up_on, :posts_voted_down_on
serialize :posts_voted_up_on, Array
serialize :posts_voted_down_on, Array
has_many :posts
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
validates_presence_of :username
validates_uniqueness_of :username
def self.authenticate(email, password)
user = find_by_email(email)
if user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt)
user
else
nil
end
end
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
现在这是我的 Voter 类,它控制赞成票和反对票。
class Voter
def initialize(post, user)
@post = post
@user = user
end
def upvote
return false unless @post.users_voted_up_by
@post.upvote += 1
@post.users_voted_up_by << @user.username
@user.good_karma += 1
@post.save && @user.save
end
def downvote
return false unless @post.users_voted_down_by
@post.upvote += 1
@post.users_voted_down_by << @user.username
@user.bad_karma += 1
@post.save && @user.save
end
end
它添加并恢复第一个罚款:
用户 1
但是,当我对另一个用户执行另一个“upvote”时,不是将它添加到数组中,而是将它添加到字符串中,如下所示:
用户1用户2
我没有正确使用线路吗?
@post.users_voted_up_by << @user.username