【问题标题】:Displaying total votes count with thumbs_up使用 thumbs_up 显示总票数
【发布时间】:2012-01-11 08:43:11
【问题描述】:

我正在尝试使用 thumbs_up gem 显示帖子的总票数,但它似乎不起作用。

这是我的代码

    def vote_up
    begin
      post = Post.find(params[:id])
      current_user.vote_for(post)
      redirect_to :back
      flash[:sucess] = "You have voted successfully"
      @votes_total = post.votes_for
    rescue ActiveRecord::RecordInvalid
        redirect_to :back
        flash[:error] = "You have already voted for this one"
    end

  end

在视图中:-

<%="Total votes = #{@votes_total}"%>

我收到“您已成功投票”的 Flash 消息,但我的投票数未显示。

这是我的日志文件中的内容:-

[1m[36m (0.3ms)[0m [1mSELECT COUNT(*) FROM "votes" WHERE "votes"."voteable_id" = 12 AND "votes"."voteable_type" = 'Post' AND "votes"."vote" = 't'[0m 0

--- 更新---

使用此代码更新我的后控制器:-

def vote_up
    begin
      post = Post.find(params[:id])
      current_user.vote_for(post)
      @votes_total = post.votes_for
      render :template => "home/index"
      flash[:sucess] = "You have voted successfully"

    rescue ActiveRecord::RecordInvalid
        redirect_to :back
        flash[:error] = "You have already voted for this one"
    end

  end

请帮忙。

【问题讨论】:

    标签: ruby-on-rails-3 ruby-on-rails-3.1 voting


    【解决方案1】:

    它不显示,因为您正在重定向。重定向时,您基本上是在执行新请求,并且前一个请求的实例变量将不再可用。 Flash 确实有效,因为它使用session。解决方案:在您要重定向到的操作中设置@votes_total 或使用render 而不是redirect_to

    【讨论】:

    • 即使渲染也看不到 :template => "home/index"
    • 注意你必须把@votes_total = post.votes_for放在render ...上面
    • 这应该可行...您确实看到Total votes =?如果您重定向到home/index 并将@votes_total = post.votes_for 添加到您的家庭控制器的索引操作中会发生什么?
    • 我在 PostsController 中定义了 post = Post.find(params[:id]) 并且索引操作在 HomeController 中会不会有问题?
    【解决方案2】:

    尝试改变

    @votes_total

    @post.votes_for 或相应的等效项

    在视图中。

    【讨论】:

    • 无法识别的方法 votes_for 是我这样做得到的错误
    猜你喜欢
    • 1970-01-01
    • 2022-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多