link_to 未触发操作

link_to is not triggering the action

我在 index.html.erb 中有以下内容(只声明了广告 post 的重要部分)

<%=link_to yay_post_path(post), :remote=>true, class:'btn-default btn' do %>
  <span class="glyphicon glyphicon-chevron-up"></span>
<% end %>
<%=link_to nah_post_path(post), :remote=>true, class:'btn btn-default' do %>
  <span class="glyphicon glyphicon-chevron-down"></span>
<%end %>

这在 route.rb

resources :posts do
   member do
    put 'yay', to: 'posts#yay'
    put 'nah', to: 'posts#nah'
  end
end

这在 PostsController

  def yay
    @post = Post.find(params[:id])
    @post.liked_by current_user
    @redirect_to @post
  end

  def nah
    @post = Post.find(params[:id])
    @post.downvote_from current_user
    @redirect_to @post
  end

注意,以上方法各有千秋。它们只是自定义方法。

当我点击 link 时,我收到 404 错误提示

cannot find /post/1/yay

解决这个问题的方法是什么?

您使用 html 方法 put 在路由器中声明路径,因此您必须相应地调整 link。正常的 link 总是 http GET,但是 rails 会在你写的时候帮助你:

<%=link_to yay_post_path(post), remote: true, method: :put, class:'btn-default btn' do %>
  <span class="glyphicon glyphicon-chevron-up"></span>
<% end %>

因此,如果 http 方法与默认方法不同,您必须明确添加它。

[编辑:在控制器中处理 js] 要在控制器中处理 js,有两个选项:

return没什么

def yay
  respond_to do |format|
    format.js do 
      @post = Post.find(params[:id])
      @post.liked_by current_user
      head :ok
    end
  end
end

注意:这将为 html 调用 return http 状态 406,这正是我想要的:)

更标准的方法是

def yay
  @post = Post.find(params[:id])
  @post.liked_by current_user
  respond_to do |format|
    format.html { @redirect_to @post }
    format.js   { head :ok }
  end
end

但这取决于您想要支持的内容(例如,是否允许回退到标准 html)。

如果你想更新视图,这是我想要的(否则他们会继续叫喊和反对,除非你处理浏览器端),你可以这样做:

def yay
  respond_to do |format|
    format.js do 
      @post = Post.find(params[:id])
      @post.liked_by current_user
    end
  end
end

并添加一个名为 yay.js.erb 的视图,其中包含

$('#yays_and_nays').hide()

或例如更新部分视图

$(#yays_and_nays').replaceWith('<% escape_javascript(render 'yay_or_nayed_status') %>');

在你的路线中...

put 'yay', to: 'posts#yay'

它的PUT,所以你还需要在link_to中包含:method=>"put"..参考这个ApiDock