Has many through and STI

Hello!

Im using ruby 1.9.2 and Rails 3.0.3.

I have the following models

class Property < ActiveRecord::Base
class Feature < ActiveRecord::Base
class DefaultFeature < Feature
class CustomFeature < Feature
class PropertyFeature < ActiveRecord::Base

One Property can have many Features, and one Feature is associated with
many
Properties (joined through PropertyFeature model). There are two kinds
of
Features: DefaultFeatures and CustomFeatures, for what Im using single
table
inheritance. Both kinds of Features have exactly the same fields, but i
need
to differentiate them in my application.
What i want to achieve, if possible, is being able to access Features
from a
Property instance like this:
a_property.features
a_property.custom_features
a_property.default_features

And also add features to a property:
a_property.custom_features << CustomFeature.new
a_property.features << CustomFeature.new

The closest solution i could think of is this one:
http://pastie.org/1499280

The problem I’m having is that when i call a_property.custom_features it
brings all features from the property: custom AND default ones.
I’ve already tried making polymorphic the belongs_to :feature
association
in the PropertyFeature model, but it raised an
ActiveRecord::HasManyThroughAssociationPolymorphicError exception, so i
assume rails is not supposed to work like that.

I’d appreciate any help on how to do this (i’ve tried everything i could
think of). Maybe my approach is wrong to begin with, in which case i’d
love
to hear a better way to to this.

thanks!


rodrei

Not fully understanding your problem, have you tried named_scope?

On Jan 26, 9:50am, Rodrigo P. [email protected] wrote:

class PropertyFeature < ActiveRecord::Base
a_property.default_features
in the PropertyFeature model, but it raised an
ActiveRecord::HasManyThroughAssociationPolymorphicError exception, so i
assume rails is not supposed to work like that.

I’d appreciate any help on how to do this (i’ve tried everything i could
think of). Maybe my approach is wrong to begin with, in which case i’d love
to hear a better way to to this.

The issue is that the :source association you’re using doesn’t
distinguish between the types. The quickest way might be to add
a :conditions hash to the has_many declarations to only return objects
with a specific type.

–Matt J.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs