简体   繁体   English

如何在Rails中为ActiveRecord列表呈现json?

[英]how i can render a json for an list of ActiveRecord in Rails?

for example, i got a list of Target in my controller 例如,我在控制器中获得了目标列表

@targets = @user.targets.all

then i want to render @targets as json result for client ajax call. 然后我想将@targets呈现为客户端ajax调用的json结果。 in Target class define, i have some column i don't want to render. 在Tar​​get类定义中,我有一些我不想渲染的列。 i know when render single @target, we can use 我知道当渲染单个@target时,我们可以使用

:only 

or 要么

:except

but, how to deal with the list? 但是,如何处理清单?

i tried 我试过了

@targets.each do |target| @ targets.each做| target | xxxx end xxxx结束

to merge the json result, failed. 合并json结果,失败。

Override as_json in your Target class and specify which columns you don't want to be rendered. 覆盖Target类中的as_json并指定您不想呈现的列。

More details here . 更多细节在这里

暂无
暂无

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

相关问题 如何在Rails中渲染复杂的json? - How can I render complex json in rails? Rails:ActiveRecord:如何提取具有关联的记录并呈现为json - Rails: ActiveRecord: How to extract records with associations and render as json Rails:如何将多个对象渲染为JSON? - Rails: How can I render multiple objects to JSON? 如何创建带有哈希的分组哈希数组而不是Rails中的ActiveRecord的选择列表? - How can I create a select list with grouped hash array of hashes instead of ActiveRecord in Rails? 如何将Rails“ render json:”和“ render_with”的结果分配给变量,以存储在表中? - How can I assign the results of a Rails “render json:” and “render_with” to a variable, for storage in a table? 当我需要连接2个表时,如何在Rails中呈现对象索引到JSON? - How can I render an index of objects to JSON in Rails, when I need to join 2 tables? 如何使用ActiveRecord从分离的脚本中调用Rails回调? - How I can invoke rails callback from separated script with ActiveRecord? 如何在 Rails 中插入一堆 ActiveRecord 对象和关系? - How can I upsert a bunch of ActiveRecord objects and relationships in Rails? rails / ActiveRecord:如何为特定属性指定其他类? - rails/ActiveRecord: How can I specify a different class for a particular attribute? 如何在Ruby脚本的Rails中使用现有的ActiveRecord模型 - How can I use existing Activerecord model in rails in ruby script
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM