Get route for base class of STI class in Rails
This will do the trick:
<% @items.map {|i| if i.class < Thing then i.becomes(Thing) else i end}.each do |item| %>
<%= link_to item.name, item %>
<% end %>
This uses the ActiveRecord function "becomes" to do an "up-cast" of all subclasses of Thing to the Thing base class. Rails STI query all subclasses using base class
You can do this:
animals = LivingThing.all.map { |r| r if r.class.superclass.name == 'Animal' }
or:animals = LivingThing.all.map { |r| r if r.class.superclass == Animal }
This should give you all the records of classes that are subclassed from the Animal class. Rails form_for that uses STI base class
Not sure if you found a solution already, but I am using the following for my forms
= form_for [@user, @post.becomes(Post)] do |f|
- f.object = @post.becomes @post.class
reference: http://thepugautomatic.com/2012/08/rails-sti-and-form-for/ Route failing using STI
Have you defined/assigned values to the @kid
or @parent
variables? If not, they will be nil
, and you'll get the cannot redirect to nil
error you've included in your question.
Please include the full code for the create
action. Otherwise we're left to trust (rather than read for ourselves) precisely what's happening in the redirect.
Your redirects might also need some work. For example, you could do:
if (@user.is_a? Kid)
redirect_to kid_path(@user)
else
redirect_to parent_path(@user)
end
...or something very similar to that. Rails STI override model_name in parent class for all subclasses
Put this in your Mapping
class:
class Mapping < ActiveRecord::Base
def self.inherited(subclass)
super
def subclass.model_name
superclass.model_name
end
end
end
Afterwards, all child classes of Mapping
will also inherit the parent's model_name
.
Related Topics
I Am Getting This Gem Install Error for Kgio Gem When I Do a Bundle Install
Current Password Can't Be Blank When Updating Devise Account
Why Is Split(' ') Trying to Be (Too) Smart
How to Validate Overlapping Times in Rails with Postgresql
How to Get Source and Variable Values in Ruby Tracebacks
Ruby/Rails Audio Conversion Plugins
How to Include Actionmailer Class in Rake Task
Implementing a Lookup Table in Rails
Using Elasticsearch to Filter Through Tags with Whitespace
Watir Changing Mozilla Firefox Preferences
Rake Aborted: Could Not Find Rspec
"Previous Post" and "Next Post" Link in Show View (Nested Resources)
How to Create Thor::Group Generators as Args of My_Command
Using Multiple Yields to Insert Content
Rails 3.1 Has_One Nested Resource: Routing Not Generating "All" Paths