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

Friday, October 21, 2022

[FIXED] How do I customize the name of an indirect has_many association in Rails?

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

Issue

In Rails, we have the has_many feature:

class Product < ApplicationRecord
  has_many :product_sales
  has_many :states, through: :product_sales
end

Is there any way I can give a custom name to one of these has_manys?

For example: instead of accessing states from Product by using @product.states, I would like to access it using @product.states_where_it_is_sold.


Solution

Yes, there is a way. Do:

class Product < ApplicationRecord
  has_many :product_sales
  has_many :states_where_sold, through: :product_sales, source: :state
end


Answered By - jvillian
Answer Checked By - Robin (PHPFixing Admin)
  • 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