diff --git a/app/api/mobile/apis/users.rb b/app/api/mobile/apis/users.rb index 0bd193f51..4950d7041 100644 --- a/app/api/mobile/apis/users.rb +++ b/app/api/mobile/apis/users.rb @@ -29,7 +29,7 @@ module Mobile logger.debug "openid ============== #{openid}" raise "无法获取到openid,请在微信中打开本页面" unless openid uw = UserWechat.where(openid: openid).first - raise "此微信号已绑定用户(#{uw.user.login}), 不能重复绑定" if uw + raise "此微信号已绑定用户(#{uw.user.login}), 不能重复绑定" if uw && uw.real? user, last_login_on = User.try_to_login(params[:login], params[:password]) raise "用户名或密码错误,请重新输入" unless user @@ -37,10 +37,15 @@ module Mobile raise "此用户已经绑定过公众号, 请换一个帐户试试" if user.user_wechat - UserWechat.create!( + if uw && !user.real? + uw.migrate_user(user) + else + UserWechat.create!( openid: openid, user: user - ) + ) + end + ws = WechatService.new ws.binding_succ_notice(user.id, "您已成功绑定Trustie平台。", user.login+"("+user.show_name+")", Time.now.strftime("%Y-%m-%d")) present status: 0, message: '您已成功绑定Trustie平台' @@ -58,25 +63,18 @@ module Mobile raise "无法获取到openid,请在微信中打开本页面" unless openid uw = UserWechat.where(openid: openid).first - if uw - uw.bindtype = 0 - uw.save - user = uw.user - user[:login] = params[:login] - user[:mail] = params[:mail] - user[:password] = params[:password] - user[:password_confirmation] = params[:password] - user[:should_confirmation_password] = true - user.save! - else - us = UsersService.new - user = us.register params.merge(:password_confirmation => params[:password], - :should_confirmation_password => true) - raise user.errors.full_messages.first if user.new_record? + raise "此微信号已绑定用户(#{uw.user.login}), 不能重复绑定" if uw && uw.real? + us = UsersService.new + user = us.register params.merge(:password_confirmation => params[:password], + :should_confirmation_password => true) + raise user.errors.full_messages.first if user.new_record? + if uw && !user.real? + uw.migrate_user(user) + else UserWechat.create!( - openid: openid, - user: user + openid: openid, + user: user ) end diff --git a/app/models/user_wechat.rb b/app/models/user_wechat.rb index 370ab8fd1..a96cabbe5 100644 --- a/app/models/user_wechat.rb +++ b/app/models/user_wechat.rb @@ -3,4 +3,24 @@ class UserWechat < ActiveRecord::Base :headimgurl, :subscribe_time, :unionid, :remark, :groupid, :user, :user_id, :bindtype belongs_to :user + + def real? + bindtype == 0 + end + + def migrate_user(u) + self.bindtype = 0 + old_user = user.id + self.user = u + self.save + + ## 主要是将comment 迁移 + User.delete(old_user) + + JournalForMessages.where(user_id: old_user).update_all(user_id: u.id) + Journal.where(user_id: old_user).update_all(user_id: u.id) + Comment.where(author_id: old_user).update_all(author_id: u.id) + Message.where(author_id: old_user).update_all(author_id: u.id) + BlogComment.where(author_id: old_user).update_all(author_id: u.id) + end end