簡體   English   中英

Ruby On Rails-link_to創建錯誤的網址

[英]Ruby On Rails - link_to creating wrong url

基本幫助在這里,但是我是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

route.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}) %>

耙路:輸出

前綴動詞URI模式控制器#Action根GET / demo#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 />

您使用的是Rails路線錯誤的方式。 您不應該使用全部捕獲路線。 為用戶可用的每個控制器操作編寫一條明確的路由。 您可以在此處閱讀有關路由的更多信息。

請嘗試按照以下步驟編輯您的路線規則。

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

謝謝

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM