【问题标题】:Acts_as_votable routing problemsActs_as_votable 路由问题
【发布时间】:2015-03-05 06:59:33
【问题描述】:

我一直在使用acts_as_votable gem,它适用于图片、cmets 和事件等。但我希望该选项也能够喜欢另一个用户。

阅读文档,我可以通过将acts_as_votable 和acts_as_voter 添加到模型中来做到这一点。

问题是我不知道如何调整我的路线以考虑到这一点,因为它的配置与其他路线略有不同。

在开发中,个人资料页面显示在 localhost:3000/@user.profile_name

路线是get '/:id', to: 'profiles#show', as: 'profile'.

使用acts_as_votable 路由通常会像这样:

resources :comments do
member do
    put "like", to: "comments#upvote"
    put "dislike", to: "commentss#downvote"
  end
end

但是我该如何调整我现有的路线以以类似的方式工作?

如果我使用

resources :profiles, only: :show, as: 'profile' do
    put 'like', on: :member
    put 'dislike', on: :member
end

这将作为 localhost:3000/profiles/@user.profile_name/like 工作。

这不适用于以下情况:

def like
  @user = User.find_by_profile_name(params[:id])
  @user.liked_by current_user
  redirect_to profile_path(@user)
end

def dislike
  @user = User.find_by_profile_name(params[:id])
  @user.unliked_by current_user
  redirect_to profile_path(@user)
end

或者我喜欢/不喜欢的按钮。

<%= link_to dislike_profile_path(@user), method: :put, class: "btn btn-success btn-xs" do %>
  <i class="fa fa-heart-o"></i> Remove Hype
<% end %>

<%= link_to like_profile_path(@user), method: :put, class: "btn btn-success btn-xs"  do %>
  <i class="fa fa-heart"></i> Hype
<% end %>

【问题讨论】:

    标签: ruby-on-rails routes


    【解决方案1】:
    resources :profiles, only: :show, path: '/' do
      member { put :like, :dislike }
    end
    

    您的链接应该可以正常工作

    注意:通过在浏览器中输入路径,它将通过 get 完成,而不是 put,所以它不会工作,但我假设你知道这一点 :-)

    【讨论】:

    • 这给了我错误No route matches [PUT] "/profiles/testband/like.testband"
    • 我的错误的,固定的答案,现在应该可以工作了 :),应该是 resources :profiles,其他更改只是装饰性的:D
    • 感谢这已修复路由工作。唯一的问题是我现在使用类似的方法出现错误。 undefined method vote' for nil:NilClass` 它突出显示了@user.liked_by current_user
    • 可能您必须将链接更改为 like_profile_path(@user.profile_name),因为它提供带有 ID 的 url,并且您正在通过 profile_name 进行搜索
    • 全部解决。我忘记将 gem 更新到最新版本。不要认为年长者支持可投票和投票者的模式。
    猜你喜欢
    • 2017-03-26
    • 1970-01-01
    • 2018-09-30
    • 2016-11-09
    • 1970-01-01
    • 2011-09-16
    • 2016-07-10
    • 2012-04-27
    • 2011-10-28
    相关资源
    最近更新 更多