【问题标题】:Rails is adding an "id" to the end of my link using the Hash MethodRails 正在使用哈希方法在我的链接末尾添加一个“id”
【发布时间】:2016-01-01 21:09:42
【问题描述】:

“a href”按计划工作,但“Link_to”在“hello”操作的末尾添加了一个“id”,将我引导至 demo/helloid 而不是 demo/hello。请参阅下面的 Rails .erb 代码

<h1>Demo#index</h1>
<p>Hello From index!!</p>

<a href="/demo/hello">Hello page 1</a><br />

<%= link_to "Hello Page 2", ({ controller: "demo", action: "hello"}) %>

在查看 HTML 源代码时,它会显示以下内容

<h1>Demo#index</h1>
<p>Hello From index!!</p>

<a href="/demo/hello">Hello page 1</a><br />

<a href="/demo/helloid">Hello Page 2</a>

路线

 Rails.application.routes.draw do
  root "demo#index" 
  #get 'demo/index'
  match ':controller(/:action(id))', :via => :get

控制器

    class DemoController < ApplicationController

    layout false

    def index
    end

    def hello
        #render('hello')
        @array = [1,2,3,4,5]
    end

    def other_hello
        redirect_to(:controller => 'demo', :action => 'index')
    end

end

【问题讨论】:

  • 能否提供routes.rb 和控制器代码?
  • 请发布您的路线文件
  • 也尝试过类似的方法,例如。 link_to "Profile", { controller: "profiles", action: "show", id: @profile}
  • 我在中编辑了控制器和路由文件
  • 我很困惑实际的问题是什么。它在做什么与您期望它做什么?

标签: ruby-on-rails-4


【解决方案1】:

您的路线在以下行不正确:

match ':controller(/:action(id))',   :via => :get   # Incorrect AND unnecessary

此外,这条路线甚至不需要存在,因为 Rails 可以使用 url_for 方法为您完成此操作:

<%= link_to "Hello Page 2", url_for(controller: "demo", action: "hello") %>

只要在 routes.rb 中分配了具有适当控制器/操作的路由,就会生成该特定路由的 URL。

> Read the Rails url_for Docs here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-11
  • 1970-01-01
  • 2011-04-06
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多