Rails namescoped model object without module prefix route path
-
25-06-2021 - |
Question
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.
I using in routes.rb
scope method instead namespace, because i wan't have "ugly" path helpers.
It looks like:
scope module: :taxonomy do
resources :taxonomies do
resources :terms
end
end
Problem is that when i want to edit taxonomy (url: taxonomies/1/edit
) i get an error:
undefined method `taxonomy_taxonomy_path'
cause my route is instead only taxonomy_path
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
my models:
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
and controllers:
module Taxonomy
class TaxonomiesController < ApplicationController
La solution
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
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.
Autres conseils
Try this in routes.rb:
namespace :taxonomy do
resources :taxonomies do
resources :terms
end
end
This will probably require you to store your controllers in a subdirectory named taxonomy
as well.
I am pretty sure you need to add a Module to your Class because of your folder structure.
app/models
├── ...
├── taxonomy
│ ├── taxonomy.rb
│ └── ...
└── ...
You can config rails to load your models located in subfolders recursively:
Config your config/application.rb
:
config.autoload_paths += Dir[ Rails.root.join('app', 'models', "taxonomy", '**/') ]
You can set this config for any folder and subfolder in your rails app.
If you do that you will not have to override an ActiveRecord's model, which is not always the best idea.
class Taxonomy < ActiveRecord::Base
...
end