如何为act_as_votable嵌套资源编写link_to?

时间:2019-04-25 16:06:38

标签: ruby-on-rails ruby-on-rails-4 routes acts-as-votable

我正在尝试对我的网站添加投票。我在项目显示页面中创建并显示了改进。我正在尝试允许用户对改进进行投票,但是我收到一个错误,我认为这与我链接“赞”按钮的方式有关。

在我的routes.rb文件中:

  resources :projects do

    resources :improvements do      
        member do
            put "like" => "improvements#upvote"
            put "unlike" => "improvements#downvote"
        end

    end
   end

我认为:

<%= link_to like_improvement_path(improvement), class: "like", method: :put do %>

Rails建议我写:

<%= link_to project_like_improvement_path(improvement), class: "like", method: :put do %>

但这不起作用。所以我尝试在我的routes.rb中这样做:

  resources :projects do

    resources :improvements

  end

   resources :improvements do       
        member do
            put "like" => "improvements#upvote"
            put "unlike" => "improvements#downvote"
        end
   end

使用原始的link_to,可以进行投票,但是单击“投票”按钮会将我带到改进的显示页面。我想留在项目页面上。

2 个答案:

答案 0 :(得分:0)

如果:

<%= link_to like_improvement_path(improvement), class: "like", method: :put do %>

然后在改进控制器的(upvote?)操作中执行以下操作:

redirect_to projects_path 在其他任何事情结束时,您都要明智地建模。 将“ projects_path”更改为页面的正确路由。

答案 1 :(得分:0)

我有同样的问题。您原始的route.rb的解决方案:

<%= link_to like_project_improvement_path(improvement.project, improvement), class: "like", method: :put do %>

您可以在改进控制器的upvote和downvote方法中编写一个redirect_to。