PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 21, 2022

[FIXED] How can I get name of through relation of has_many relation in rails?

 October 21, 2022     has-many, has-many-through, ruby-on-rails, ruby-on-rails-4     No comments   

Issue

I have :

class Foo
   has_many :bar
   has_many :baz, through :bar
end


class FooTwo
   has_many :barTwo
   has_many :baz, through :barTwo
end

I need be abble to get through relation of baz association, like :

Foo.first.baz.relation_through #<=> Foo.first.bar
FooTwo.first.baz.relation_through #<=> Foo.first.barTwo

if it's impossible, can I get just the name? like :

Foo.first.baz.get_relation_through_name # "bar"
FooTwo.first.baz.get_relation_through_name # "barTwo"

Solution

Try this

Foo.reflect_on_all_associations.find { |association| association.name == :baz}.options[:through]


Answered By - Sahil Goel
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing