Rails #url_for在解析命名空间嵌套资源的URL时重复名称空间前缀

时间:2016-05-02 16:42:40

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

向大家致意,

我有以下内容:

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以这种方式工作,因为它在SimpleForm中由#simple_form_for内部使用。

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

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),以便它解析为实际路线。怎么可能呢?

1 个答案:

答案 0 :(得分: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