为什么我的 if else 语句不能在控制器中工作 [Rails 4]
Why isn't my if else statement working in controller [Rails 4]
我正在尝试让用户能够通过重新点击投票按钮来删除他的投票
这是我的控制器
def upvote
if current_user.voted_up_on? @post
@post = Post.find(params[:id])
@currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
@currentUserLikes.destroy_all
else
@post = Post.find(params[:id])
@post.upvote_by current_user
@post.create_activity :like,
owner: current_user,
recipient: @post.user
end
end
def downvote
@post = Post.find(params[:id])
@post.downvote_by current_user
@post.create_activity :dislike,
owner: current_user,
recipient: @post.user
end
我尝试将 if else 放在索引中,但它变得太复杂了,
为什么它不起作用?
请注意,currentUserLike 是为了破坏用户的 upvote 操作。
和
upvote 按钮不再工作,我没有 post 索引,因为当我没有更改控制器时我没有将它改回来
当您检查用户是否投票时,@post 似乎未设置为 post。尝试将 @post = Post.find(params[:id]) 移动到您的 if 语句上方。
试试这个:
def upvote
@post = Post.find(params[:id])
if current_user.voted_up_on? @post
@currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
@currentUserLikes.destroy_all
else
@post.upvote_by current_user
@post.create_activity :like,
owner: current_user,
recipient: @post.user
end
end
我正在尝试让用户能够通过重新点击投票按钮来删除他的投票
这是我的控制器
def upvote
if current_user.voted_up_on? @post
@post = Post.find(params[:id])
@currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
@currentUserLikes.destroy_all
else
@post = Post.find(params[:id])
@post.upvote_by current_user
@post.create_activity :like,
owner: current_user,
recipient: @post.user
end
end
def downvote
@post = Post.find(params[:id])
@post.downvote_by current_user
@post.create_activity :dislike,
owner: current_user,
recipient: @post.user
end
我尝试将 if else 放在索引中,但它变得太复杂了, 为什么它不起作用? 请注意,currentUserLike 是为了破坏用户的 upvote 操作。 和 upvote 按钮不再工作,我没有 post 索引,因为当我没有更改控制器时我没有将它改回来
当您检查用户是否投票时,@post 似乎未设置为 post。尝试将 @post = Post.find(params[:id]) 移动到您的 if 语句上方。
试试这个:
def upvote
@post = Post.find(params[:id])
if current_user.voted_up_on? @post
@currentUserLikes = PublicActivity::Activity.where(trackable_id: @post.id, owner_id: current_user.id, key: "post.like")
@currentUserLikes.destroy_all
else
@post.upvote_by current_user
@post.create_activity :like,
owner: current_user,
recipient: @post.user
end
end