没有模块前缀路由路径的Rails名称作用域模型对象 [英] Rails namescoped model object without module prefix route path

查看:103
本文介绍了没有模块前缀路由路径的Rails名称作用域模型对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Rails路由器和表单生成器有一点问题. 我的应用程序具有用于模型和控制器的命名空间模块.模块用于更轻松地抽象到另一个项目.

i have problem little bit with Rails router and form generator. My application have namespaced modules for models and controllers. Module is used to easier abstraction to another projects.

我在routes.rb范围方法中使用了命名空间,因为我没有丑陋"的路径助手.

I using in routes.rb scope method instead namespace, because i wan't have "ugly" path helpers.

它看起来像:

scope module: :taxonomy do
  resources :taxonomies do
    resources :terms
  end
end

问题是,当我要编辑分类法(URL:taxonomies/1/edit)时,出现错误:

Problem is that when i want to edit taxonomy (url: taxonomies/1/edit) i get an error:

undefined method `taxonomy_taxonomy_path'

因为我的路线只是taxonomy_path

有什么方法可以到达form_for @taxonomy来识别该路径是作用域?没有使用的form_for @taxonomy, url: taxonomy_path(@taxonomy)不能治愈.因为respond_with @taxonomy中控制器方法中的@taxonomy对象始终引用taxonomy_taxonomy_url

is there any way how reach form_for @taxonomy to recognize that route is scoped? without used form_for @taxonomy, url: taxonomy_path(@taxonomy) which is not cure. Because @taxonomy object in controller methods within respond_with @taxonomy always refereces to taxonomy_taxonomy_url

我的模特:

module Taxonomy
  class Taxonomy < ActiveRecord::Base
    has_many :taxonomy_terms, inverse_of: :taxonomy
    has_many :terms, through: :taxonomy_terms
  class Term < ActiveRecord::Base
    has_one :taxonomy_term, inverse_of: :term
    has_one :taxonomy, through: :taxonomy_term

和控制器:

module Taxonomy
  class TaxonomiesController < ApplicationController

推荐答案

您可以通过以下方式覆盖ActiveRecord的模型命名:

You can override ActiveRecord's model naming by:

module Taxonomy
  class Taxonomy < ActiveRecord::Base
    def self.model_name
      ActiveModel::Name.new("Taxonomy")
    end
  end
end

这将覆盖ActiveRecord的默认命名生成,因为它位于Taxonomy模块下,因此会为Taxonomy类生成taxonomy_taxonomy名称. 它应该可以解决您的路由名称问题,并根据您的需要生成正确的路由名称.

This overrides ActiveRecord default naming generation which generates taxonomy_taxonomy name for the Taxonomy class since it is under Taxonomy module. It should solve your routing name problem and generate a proper route name as you wish.

这篇关于没有模块前缀路由路径的Rails名称作用域模型对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆