0

I don't understand what {article: :categories} means for the below code. I have read the documentation, but it does not show an example like includes(z => {x: :y}). Can somebody put this to a different form that I can understand? What exactly is x: :y?

@articles = ArticleBase.includes(media.to_sym => { article: :categories })

In addition, if I want to add another condition to it (.includes(media.to_sym => :article)), would the code below be alright syntax-wise?

@articles = ArticleBase.includes(media.to_sym => { article: :categories }, media.to_sym => :article)
anothermh
  • 9,815
  • 3
  • 33
  • 52
  • It [`includes`](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-includes) a (nested) relationship in the result set so you don't need to write multiple queries. The "primary" relation is specified by `media.to_sym`, i.e. dynamically. Have a look at your rails console – it should output the SQL query which might help to understand what's going on. (depends on your DB schema) – Stefan Sep 02 '20 at 08:06
  • Have you read [the documentation](https://apidock.com/rails/ActiveRecord/QueryMethods/includes)? Also, [these docs](https://api.rubyonrails.org/classes/ActiveRecord/QueryMethods.html#method-i-includes) are quite good. There are also plenty of in-depth [blog posts](https://engineering.gusto.com/a-visual-guide-to-using-includes-in-rails/) online about it, and related [questions on StackOverflow](https://stackoverflow.com/q/1208636/1954610). – Tom Lord Sep 02 '20 at 08:18
  • Regarding your latter question: It's valid syntax (I think?... Try running it to see!), but that specific example is pointless -- since you're only including an already-included relation. – Tom Lord Sep 02 '20 at 08:20

1 Answers1

0

Whats happening here is that they are just dynamically assigning a hash key in the hash that's provided as an argument to #includes:

"foo".then do |media|
  { media.to_sym => { article: :categories }}
end
=> {:foo=>{:article=>:categories}}

This is possible when you are using the hash rocket hash syntax but not the colon syntax.

{ media.to_sym: bar } # Raises a SyntaxError

would the code below be alright syntax-wise?

@articles = ArticleBase.includes(media.to_sym => { article: :categories }, media.to_sym => :article)

Not really. It won't raise a syntax error but neither will it do what you're intending. When you have a hash literal with duplicate keys Ruby does not warn you - it just overwrites with the last given value for the key.

"foo".then do |media|
  { media.to_sym => { article: :categories }, media.to_sym => :acticle }
end
# => {:foo=>:acticle}

Its also unclear what this code even is supposed to accomplish since { article: :categories } will include article.

max
  • 96,212
  • 14
  • 104
  • 165