简体   繁体   English

Rails 5.1 API渲染JSON倍增关系

[英]Rails 5.1 api render json doubling relationships

With Rails 5.1.1 I have a problem where rendering JSON is somehow "doubling" the number of relationships. 使用Rails 5.1.1时,我遇到了一个问题,即呈现JSON会使关系数量“加倍”。

There is a has_many / belongs_to relationship, nothing fancy. 有一个has_many / belongs_to关系,没什么好看的。 A "user" has many "codes". 一个“用户”有许多“代码”。 Stepping through the users_controller#update method I see the following: 逐步执行users_controller#update方法,我看到以下内容:

Check what is coming in from the params: 检查从参数传入的内容:

(byebug) user_params['codes_attributes'].count
2

Check what is saved after @user.update(user_params) was called: 检查调用@user.update(user_params)之后保存的内容:

(byebug) @user.codes.count
   (0.4ms)  SELECT COUNT(*) FROM "codes" WHERE "codes"."user_id" = ?  [["user_id", 85]]
2

Lastly, a straight as_json doubles via the relationship as well: 最后,直接的as_json通过该关系加倍:

(byebug) @user.codes.as_json.count
4

Check what is output from as_json ( to_json is the same): 检查as_json输出( to_json相同):

(byebug) @user.as_json(include: [:friend, :codes])['codes'].count
4
(byebug) @user.codes.count
   (0.3ms)  SELECT COUNT(*) FROM "codes" WHERE "codes"."user_id" = ?  [["user_id", 85]]
2

And here we can see that somehow the number of relationships magically doubled! 在这里我们可以看到,关系的数量以某种方式神奇地翻了一番! Any ideas? 有任何想法吗?

UPDATE UPDATE

I was making use of a custom function to save associations (autosave_associated_records_for_codes) which seems to have introduced the problem. 我正在使用一个自定义函数来保存关联(autosave_associated_records_for_codes),这似乎已经引入了问题。 I've commented it out for now but will try to revisit why exactly it was doubling things up. 我目前已将其注释掉,但将尝试重新审视它究竟是为什么将事情加倍的原因。 Once I figure out the exact cause will reply back with a solution. 一旦我弄清楚了确切原因,就会以解决方案回覆。

I don't have much experience in rails, though i suggest you to try this. 尽管我建议您尝试一下,但我在Rails上没有太多经验。 Iam not sure about it, but you should give it a try. 我不确定,但是您应该尝试一下。

  def get_codes_count
    self.codes.count
  end

And then if you want a count then you can just do 然后,如果您想计数,就可以做

  @user.as_json(method: :get_codes_count)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM