Rails 3 routes and modules

2019-07-10 02:30发布

问题:

I have a AR model inside a module

class Long::Module::Path::Model < ActiveRecord::Base
end

and want to use following routes (without the module names, because it's easier to write and remember)

resources :models

buts Rails 3 always wants to use a URL like

long_module_path_model_url

Is there are way to change this behavior?

Hope anyone out there can help me?

Mario

回答1:

I'm a little curious why you're referencing a model when talking about routing which only handles the controller level; but this article should be helpful: R3 Controller Namespaces and Routing

"If you want to route /photos (without the prefix /admin) to Admin::PostsController, you could use:

scope :module => "admin" do
  resources :posts, :comments
end

"

If you'd like the named paths to change, you can use :as, as specified here: R3 Prefixing the Named Routes Helpers

So I'm guessing something along the lines of

1:

scope :module => 'long/module/path' do
   resources :model, :as => :model
end

or 2:

scope :module => 'long' do
  scope :module => 'module' do 
   scope :module => 'path' do
    resources :model, :as => :model
   end end end

Is what you're looking for.



回答2:

resources :your_looooooong_model_name, :as => :short

Would give you shorts_url, etc.



回答3:

I know this is an old question, but the others misunderstood your question and didn't solve your problem.

You need to override the model_name method as below:

class Long::Module::Path::Model < ActiveRecord::Base
  def self.model_name
    ActiveModel::Name.new(Long::Module::Path::Model, nil, "YourNewModelName")
  end
end

Credit goes to this comment.