0

I have a CourseQuestion model in my app.

I use redirect_to @discussible in my controllers, where @discussible could be of different class (therefore redirect is to a different URL).

But I need to redirect CourseQuestion models to question_path, not course_question_path which is default.

I don't need to change routes (routes are fine), just need rails to deduce specific named path for a model.

Any good way to do that?

aristofun
  • 375
  • 3
  • 18
  • Possible duplicate of [How to rename REST routes in URL?](http://stackoverflow.com/questions/5012255/how-to-rename-rest-routes-in-url) – Nic Nilov Jul 08 '16 at 17:32
  • I don't need to change routes (routes are fine), just need rails to deduce specific named route for a model. – aristofun Jul 08 '16 at 17:47
  • Isn't this done with `resources :apples, :as => "cars"`, mentioned by the link? – Nic Nilov Jul 08 '16 at 17:49
  • `resources :apples, :as => "cars"` changes the routes. I need to fit model with existing route names. – aristofun Jul 08 '16 at 18:31
  • As pointed out in [Rails Routing docs](http://guides.rubyonrails.org/routing.html#naming-routes), `:as` changes the named route helper according to its argument while keeping the route path intact. the `:path` option, in turn, modifies both. If this doesn't help you, please show your routes and relevant controller and models. – Nic Nilov Jul 08 '16 at 18:36
  • The point is that i don't want to change neither named routes nor pathes! – aristofun Jul 08 '16 at 18:46

2 Answers2

1

Something I've done, but somehow feels like a hack is to override the model_name method of the model.

In your case, you could do:

class CourseQuestion
  def self.model_name
    ActiveModel::Name.new(self, nil, "Question")
  end

# if your course_question belongs_to :question, to prevent some unwanted bugs, where course_questions/25 would map to questions/25, add a to_param method that returns the id of the question, as such
  def to_param
   question_id.to_s # Be sure to stringify the id for routes
  end
end
oreoluwa
  • 5,553
  • 2
  • 20
  • 27
1

A questionable module to include in models, changing only #route_key and #singular_route_key methods:

module DemodulizedRouteKeys
  extend ActiveSupport::Concern

  class_methods do
    def model_name
      ## this would demodulize all namings:
      # ActiveModel::Name.new self, nil, super.name.demodulize
      super.tap do |name|
        route_key = name.name.demodulize.underscore
        name.define_singleton_method(:route_key) { route_key.pluralize }
        name.define_singleton_method(:singular_route_key) { route_key }
      end
    end
  end
end
Mirko
  • 5,207
  • 2
  • 37
  • 33