【问题标题】:Rails #url_for repeats namespace prefix when resolving a url for a namespaced nested resourceRails #url_for 在解析命名空间嵌套资源的 url 时重复命名空间前缀
【发布时间】:2016-05-02 16:42:39
【问题描述】:

大家好,

我有以下:

routes.rb

 namespace :hr do
    resources :employees do
      resources :skills
    end
  end

还有那些模型:
hr/skills.rb

class Hr::Skill < ApplicationRecord
end  

hr/employees.rb

class Hr::Employee < ApplicationRecord

end

我正在尝试使 #url_for 解析为 hr_employee_skills_path(@employee, @skill)。我需要 #url_for 以这种方式工作,因为 #simple_form_for 在 SimpleForm 内部使用它。

我尝试了 #url_for 的不同组合来为我提供所需的 url 路径生成器,但没有一个起作用:

url_for [Hr::Employee.new, Hr::Skill.new]
NoMethodError: undefined method `hr_employee_hr_skills_url' for main:Object

还有这个:

url_for [:hr, Hr::Employee.new, Hr::Skill.new]
NoMethodError: undefined method `hr_hr_employee_hr_skills_url' for main:Object

我只需要#url_for 调用hr_employee_skills_path(employee, skill) 以便它解析为实际路线。这怎么可能?

【问题讨论】:

    标签: ruby-on-rails ruby simple-form ruby-on-rails-5 url-for


    【解决方案1】:

    查看链接,但您可以使用该模块的一个选项来帮助解决此问题:

    module Hr
      def self.use_relative_model_naming?
        true
      end
    end
    

    这就允许这样做:

    url_for([:hr, Hr::Employee.first, Hr::Skill.first, only_path: true])
     => "/hr/employees/1/skills/1"
    

    https://coderwall.com/p/heed_q/rails-routing-and-namespaced-models

    【讨论】:

    • 我正在处理一个包含多个单元的大型项目,使用完全不相关的模型;不幸的是,模型命名空间可能是必要的。
    • 我更新了原始答案,因为原始响应不是您可以在您的场景中使用的。
    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-02
    • 2011-02-17
    • 2011-02-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多