I am using Ruby on Rails v3.2.2. I have following associations with an alias_method used for a has_many :through association, this way:
class Resource < ActiveRecord::Base
has_many :article_associations
alias_method :post_associations, :article_associations
has_many :users, :through => :post_associations
end
When I execute the @article.users I get the following error:
ActiveRecord::HasManyThroughAssociationNotFoundError
Could not find the association :post_associations in model Article
Why it happens? Is there a way to make it to work as expected? That is, how to properly return @article.users through the “aliased” :post_associations?
Note: I would like to “state” / “use” the :post_associations in the has_many :users, :through => :post_associations statement because I am trying to “dynamically build” (that is, metaprogramming) the has_many :through association.
The Ruby on Rails Framework Trace is:
activerecord (3.2.2) lib/active_record/reflection.rb:501:in `check_validity!'
activerecord (3.2.2) lib/active_record/associations/association.rb:26:in `initialize'
activerecord (3.2.2) lib/active_record/associations/collection_association.rb:24:in `initialize'
activerecord (3.2.2) lib/active_record/associations/has_many_through_association.rb:10:in `initialize'
activerecord (3.2.2) lib/active_record/associations.rb:157:in `new'
activerecord (3.2.2) lib/active_record/associations.rb:157:in `association'
activerecord (3.2.2) lib/active_record/associations/builder/association.rb:44:in `block in define_readers'
...
I don’t see a reason why you need to alias_method name your association.
Instead you could directly do something like this,
Another Solution
you need to do either of this
or