Rails:带有do块的link_to不起作用

时间:2017-10-06 22:17:59

标签: ruby-on-rails ruby views helper link-to

当'link_to'在没有阻止的情况下使用时,它可以完美地运行:

<%= link_to "Ololo", {controller: "posts", action: "upvote", id: post.id}, method: :put, remote: true, class:"nav-link" %>

但是当我尝试使用阻塞时,最终会出现错误:

        <%= link_to {controller: "posts", action: "upvote", id: post.id}, method: :put, remote: true, class:"nav-link" do %>
            <%= image_tag('icons/candy.svg', alt: "Candies", class:"rounded-circle icon-nav") %> 
            <%= post.get_upvotes.size %> 
        <% end %>

以下是错误消息:

SyntaxError (/home/alex/test/app/views/application/_votes_exp.html.erb:5: syntax error, unexpected ':', expecting '}'
...r.append=  link_to {controller: controller_name, action: "up...
...                               ^
/home/alex/test/app/views/application/_votes_exp.html.erb:5: syntax error, unexpected ',', expecting '}'
...troller_name, action: "upvote", id: entity.id}, method: :put...
...                               ^
/home/alex/test/app/views/application/_votes_exp.html.erb:5: syntax error, unexpected tLABEL
...pvote", id: entity.id}, method: :put, class:"nav-link", remo...
...                               ^
/home/alex/test/app/views/application/_votes_exp.html.erb:5: syntax error, unexpected ',', expecting keyword_end
...method: :put, class:"nav-link", remote: true do @output_buff...
...                               ^
/home/alex/test/app/views/application/_votes_exp.html.erb:49: syntax error, unexpected keyword_ensure, expecting end-of-input):

所以它似乎不理解文字哈希,但是,我太新手了解什么是错的...感谢任何帮助!

P.S。:我无法删除文字哈希,因为link_to搞乱了css类(将类添加为地址的一部分)。此外,我必须使用旧的参数样式而不是'upvote_post_path'之类的东西,因为控制器名称由变量表示(在我的示例中,为了代码的可读性而减少)

更新

的routes.rb

Rails.application.routes.draw do
  root to: "home#index"

  resources :posts do 
    member do
      put "upvote", to: "posts#upvote"
    end
  end
end

1 个答案:

答案 0 :(得分:2)

开头大括号的事情如下:

some_method { a: 'b' }

含糊不清。 {可以像a.each { ... }中那样打开一个块,也可以打开一个哈希文字。你认为它是后者,但Ruby认为它是前者,那就是错误的来源。

最简单的解决方案是使用方法调用括号:

<%= link_to({controller: "posts", action: "upvote", id: post.id}, method: :put, remote: true, class:"nav-link") do %>
           ^--------------------------------------------------------------------------------------------------^

您还可以使用变量将左大括号移动到其他位置:

<% upvote_post = { controller: 'posts', action: 'upvote', id: post.id } %>
<%= link_to upvote_post, method: :put, remote: true, class:"nav-link" do %>

这一个:

link_to "Ololo", {controller: "posts", ... 

工作正常,因为第一个参数("Ololo",)通过告诉Ruby它正在解析参数列表来消除任何歧义。