Get Route for Base Class of Sti Class in Rails

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



Leave a reply



Submit