【问题标题】:ActionController::UrlGenerationError in Accounts#plansActionController::UrlGenerationError in Accounts#plans
【发布时间】:2015-11-01 07:14:28
【问题描述】:

这是我在路线文件中的路线

get '/signup/:plan/:discount' =>'accounts#new', plan: nil, discount: 0, as: :new_account

我在我的 html 文件中调用这些路由,如下所示

<a href="<%= new_account_url('$129', params[:discount]) %>" class="signup"><img src="/images/sign-up.png"></a>

在后端运行 rake routes 命令后,我得到关注

 new_account GET    /signup/:plan/:discount(.:format)
   accounts#new {:plan=>nil, :discount=>0}

但我不知道它给我错误的路线有什么问题

No route matches {:action=>"new", :controller=>"accounts", :discount=>nil, :format=>nil, :plan=>"$129"} missing required keys: [:discount]

【问题讨论】:

  • params[:discount]的值是多少?
  • 还可以尝试将路由中的discount: 0 更改为discount: nil
  • 我也尝试将折扣设为 nil 但仍然无法正常工作。并且 params[:discount] 在值来时不是强制性的,然后用 nil 或 0 替换。
  • 您是如何获得params[:discount] 的?我怀疑params[:discount] 没有传递给视图。
  • 但是plan: nil 没有任何意义.. 可能是0 或其他一些默认值更有意义..

标签: ruby-on-rails ruby-on-rails-4 routes


【解决方案1】:

如果你有一个 url '/signup/:plan/:discount',那么 :plan:discount 都是必需的键。您永远不能将这些键的值设为nil。如果你有,你将永远得到你现在遇到的错误。

由于这些值是可选的,我的建议是将它们作为查询参数发送,并在控制器内部进行检查。

尝试重新组织路由定义:

get '/signup' =>'accounts#new', as: :new_account

您也可以使用link_to 重写网址,如下所示:

<%= link_to  new_account_path(plan: '$129', discount: params[:discount]), class: "signup" do %>
  <img src="/images/sign-up.png" />
<% end %>

现在,您将始终拥有如下网址:

/signup?plain="xx"&discount="xx"

【讨论】:

    【解决方案2】:

    您的 params[:discount] 缺少一个值,因此当您在路由中调用它时,它没有被分配:

    {:action=>"new", :controller=>"accounts", :discount=>nil, :format=>nil, :plan=>"$129"}
    

    由于您已将:discount 设置为路由的必需部分,因此您需要在调用帮助程序时向其传递一个值。


    要做的最重要的事情是确保您的params[:discount] 变量被填充。如果没有,您不妨使用bound parameters

    get '/signup/:plan(/:discount') =>'accounts#new', discount: 0, as: :new_account
    

    这将使:discount 参数变得不必要。


    其次,您应该在创建链接时始终使用link_to。它使您的 HTML 保持最新并符合规范:

    <%= link_to new_account_path("$129", params[:discount]), class: "signup" do %>
       <%= image_tag "sign-up.png" %>
    <% end %>
    

    -

    您还需要确保将路线设置在适当资源的范围内:

    #config/routes.rb
    resources :accounts, only: [:new], path_names: { new: "signup" } do
       get ":plan(/:discount)", on: :new
    end
    

    【讨论】:

      猜你喜欢
      • 2015-10-26
      • 1970-01-01
      • 1970-01-01
      • 2015-11-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多