【问题标题】:Ruby On Rails - link_to creating wrong urlRuby On Rails - link_to 创建错误的 url
【发布时间】:2015-06-02 03:35:45
【问题描述】:

这里有基本的帮助,但我是 Ruby On Rails 的新手。 Windows 7 上的 Rails 版本 4.1.7。

我希望看到为链接创建的不同 url。代码和问题描述如下。

感谢您的帮助!

-T

控制器:

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

    def lynda
        redirect_to("http://lynda.com")
    end
end

routes.rb:

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

index.html.erb('/demo/index'):

<h1>Demo#index</h1>
<p>Hello From Index</p>
<a href="/demo/hello">Hello Page 1</a><br />
<%= link_to( "Hello page 2c", {action: "hello" })%> <br />
<%= link_to("Hello with Parameters", {action:"hello", page: 5, id: 20}) %>

rake 路线:输出

前缀动词 URI 模式控制器#Action 根 GET / 演示#index GET /:controller(/:action(:id))(.:format) :controller#:action

来自 index.html 的结果源:

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

<a href="/demo/hello">Hello Page 1</a><br />
<a href="/demo">Hello page 2c</a> <br />
<a href="/demo/hello20?page=5">Hello with Parameters</a>

问题:

我希望“Hello page 2c”链接的 href 为“/demo/hello”。

我还希望“带参数的 Hello”链接的 href 为“/demo/hello/20?page=5”

不知道进一步看什么。

我尝试了不同的方法来格式化 link_to,但它们都给出了相同的结果。

前:

<%= link_to( "Hello page 2c", {:action => "hello" })%> <br />
<%= link_to("Hello with Parameters", {:action => "hello", page: 5, id: 20}) %><br />

<%= link_to "Hello page 2c", action: "hello" %> <br />
<%= link_to "Hello with Parameters", action: "hello", page: 5, id: 20 %><br />

<%= link_to( "Hello page 2c", {controller: "demo", action: "hello" })%> <br />
<%= link_to("Hello with Parameters", {controller: "demo", action:"hello", page: 5, id: 20}) %><br />

【问题讨论】:

    标签: ruby-on-rails link-to


    【解决方案1】:

    尝试如下编辑您的路由规则。

    match ':controller(/:action(/:id))', :via => :get
    

    谢谢

    【讨论】:

      【解决方案2】:

      您以错误的方式使用 rails 路线。你不应该使用 catch all 路线。为用户可用的每个控制器操作编写显式路由。你可以阅读更多关于路由here的信息。

      【讨论】:

      • 感谢您的回复。我正在使用教程来学习 Rails,这是他们使用的代码。我知道有更好的方法来做路由只是还没有遇到过这个教训。所以,虽然不是正确的 Rails,但这段代码不应该像我预期的那样工作?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多