使用rails

时间:2015-08-31 11:21:58

标签: ruby-on-rails activerecord

我有一个表'喜欢',列有business_id,user_id和者喜欢(0,1)以及一个'change_like_status'函数。

现在每次调用函数时,如果值为1,则将其设置为0(反之亦然),如果记录不存在,则创建值为1的值。

first_or_create方法工作得很好但是如何在使用此方法时切换列'likes'的值?

这是我的功能:

def change_like_status
  if current_user.present?
    status = Like.where("business_id = ? AND user_id = ?",params['id'],current_user.id).first_or_create(:business_id => params['id'],:user_id => current_user.id,:liked => '1')
    abort status.inspect
  else
    return render :json => {:status => false,:msg=>"You need to sign in before performing this action."}
  end
end

2 个答案:

答案 0 :(得分:4)

在您的控制器中,进行更改

def change_like_status
  if current_user
    status = Like.create_or_change_status(params[:id], current_user.id)
  else
    return render json: { status: false, msg: "You need to sign in before performing this action." }
  end

在模型like.rb文件中,添加方法

def self.create_or_change_status(business_id, user_id)
   status = where(business_id: business_id, user_id: user_id).first
   if status.nil?
      status = create({business_id: business_id, user_id: user_id, liked: 1})
   else
      status.update_attributes(liked: !status.liked)
   end
   status
end

答案 1 :(得分:1)

def change_like_status
  if current_user
    current_user.likes.find_by(business_id: params[:id]).switch_status!
  else
    return render json: { status: false, msg: "You need to sign in before performing this action." }
  end
end

class Like
  def switch_status!
    self.update_column :liked, !liked
  end
end

其他方法应该是那样的

class Like
  def switch_status!
    self.update_column :liked, !liked
  end
end


class User
  def likes id
    likes_for_business id
  end

  def likes_for_business(id)
    likes.find_by(business_id: id) || likes.create(:business_id: id, liked: true)
  end
end

# controller
current_user.likes(params[:id]).switch_status!