Apparently redundant ActiveRecord has_many definition

I apply style associations has and belongs to manyto the project I was working on, but since I wanted to get additional information in my connection model, I implicitly configure it through a more complex belongs_to/ has_manyinstead has_and_belongs_to_many. After I came across this, I found out that I need both of these definitions in my User model (and the same thing in the Show Model):

has_many :saved_shows
has_many :shows, :through :saved_shows

Everything works, and my question is more about Rails syntax design because I want to make sure I don't miss the big picture here: why is the first one needed? If we establish that the user can access the list of shows through an intermediate link with a non-standard name saved_shows, why also install has_many :saved_shows?

I guess I'm not the first to get into this problem, so I'm curious why Rails requires this seemingly redundant definition. Is it just a poorly chosen syntax or is there some deeper design behind it?

+3
source share
1 answer

Rails uses a parameter :throughto refer to another association that you have already defined. I think he does this so that you can first establish complex associations without defining them and referring to them on the same line.

For example, consider this (optionally complex) example:

has_many :users, :class_name => 'Person', :foreign_key => 'owner_id'
has_many :tasks, :through => :users, :class_name 'Job'

There is no pure way to express all this information in a string.

( , ), . , has_many :tasks has_many :milestones, :through => :tasks, @user.tasks, @user.milestones.

, ( , , , ), , has_many :through.

? , , .

+3

Source: https://habr.com/ru/post/1769315/


All Articles