My Rails views and controllers are littered with redirect_to
, link_to
, and form_for
method calls. Sometimes link_to
and <
hackish,but just another one to the list of solutions.
class Parent < ActiveRecord::Base; end
Class Child < Parent
def class
Parent
end
end
works on rails 2.x and 3.x
The cleanest solution I found is to add the following to the base class:
def self.inherited(subclass)
super
def subclass.model_name
super.tap do |name|
route_key = base_class.name.underscore
name.instance_variable_set(:@singular_route_key, route_key)
name.instance_variable_set(:@route_key, route_key.pluralize)
end
end
end
It works for all subclasses and is much safer than overriding the entire model name object. By targeting only the route keys, we solve the routing problems without breaking I18n or risking any potential side effects caused by overriding the model name as defined by Rails.
I suggest you take a look at : https://stackoverflow.com/a/605172/445908, using this method will enable you to use "form_for".
ActiveRecord::Base#becomes
Use type in the routes:
resources :employee, controller: 'person', type: 'Employee'
http://samurails.com/tutorial/single-table-inheritance-with-rails-4-part-2/
I had the same problem. After using STI, the form_for
method was posting to the wrong child url.
NoMethodError (undefined method `building_url' for
I ended up adding in the extra routes for the child classes and pointing them to the same controllers
resources :structures
resources :buildings, :controller => 'structures'
resources :bridges, :controller => 'structures'
Additionally:
<% form_for(@structure, :as => :structure) do |f| %>
in this case structure is actually a building (child class)
It seems to work for me after doing a submit with form_for
.
I'm in favor of using PolymorphicRoutes
or url_for
to dynamically generate routes based on the resource, any namespace, etc.
https://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html
https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html
polymorphic_url([:admin, @article, @comment])
# => admin_article_comment_url(@article, @comment)
edit_polymorphic_path(@post)
# => "/posts/1/edit"
With admin
namespace
url_for([:admin, Role])
# => "admin/roles" # index
url_for([:admin, Role, action: :new])
# => "admin/roles/new" # new
url_for([:admin, @role])
# => "admin/roles/1" # show; for destroy, use link "method: :delete"
url_for([:edit, :admin, @role])
# => "admin/roles/1/edit" # edit