【问题标题】:Rails "No route matches" when using param and no args to route helper使用参数和无参数路由助手时,Rails“无路由匹配”
【发布时间】:2020-08-07 16:17:04
【问题描述】:

config/routes.rb:

resources :companies, param: :uid

尝试使用不带任何参数的路由助手会导致错误,因为 Rails 找到 @company 并在其上调用 id 得到 21520,但这与路由键 company_uid 不匹配。

new_company_path 
# => ActionController::UrlGenerationError: No route matches {:action=>"new", :company_id=>"21520"}, missing required keys: [:company_uid]

如果我直接传递值,它可以正常工作:

new_company_path(@company.uid) #=> "/companies/SP-3591/new"
new_company_path(@company_uid: company.uid) #=> "/companies/SP-3591/new"

有没有办法告诉 Rails 该属性是uid,所以它调用它而不是id,使对new_company_path 的无参数调用起作用?

【问题讨论】:

  • 你的路线是什么样的?

标签: ruby-on-rails ruby routes


【解决方案1】:

我认为您可以像这样在模型中添加to_param 方法

class SomeModel
  def to_param
    uid
  end
end

参考文档here 或者你可以试试friendly_url gem

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 2013-06-19
    • 2021-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    相关资源
    最近更新 更多