Preassemble Models

Now I'm trying to call my model and spit out its results in json / xml format. My only problem is that my database associations are not loading or querying.

I can usually run this

@campaign = Campaign.find (: all)

Then get the number of hits by calling @campaign[0].hitsthrough has_many :hits.

But if you debug the output, it only calls the columns in the table. How would you do this by placing it next to your request?

In the example:

  <campaign>
    <category> website </category>
    <created-at type = "timestamp"> 2009-01-24 14:49:02 -0800 </created-at>
    <end-at type = "date"> 2009-01-24 </end-at>
    <id type = "integer"> 14 </id>
    <is-watched type = "integer"> 1 </is-watched>
    <name> Lets </name>
    <slug> c5334415da5c89384e42ce6d72609dda </slug>
    <start-at type = "date"> 2009-01-24 </start-at>
    <user-id type = "integer"> 5 </user-id>
  </campaign>

Then, instead, add another column, but with the number of hits.

  <campaign>
    <category> website </category>
    <created-at type = "timestamp"> 2009-01-24 14:49:02 -0800 </created-at>
    <end-at type = "date"> 2009-01-24 </end-at>
    <id type = "integer"> 14 </id>
    <is-watched type = "integer"> 1 </is-watched>
    <name> Lets </name>
    <slug> c5334415da5c89384e42ce6d72609dda </slug>
    <start-at type = "date"> 2009-01-24 </start-at>
    <user-id type = "integer"> 5 </user-id>
    <hits type = "integer"> 123412 </hits>
  </campaign>
+3
source share
2

ActiveRecord find() : include, .

, , , :

@campaign = Campaign.find(: ,: include = > : hits)

, [0]. [1] .. SELECT.

@campaign [0].to_json

- , "", , : to_json, .

@campaign [0].to_json (: include = > : hits)

+7

, , , hits_count . .

counter_cache ActiveRecord Associations

+1

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


All Articles