Rails 3:呈现 JSON 中对象数组的某些属性
在我看来,我正在尝试将一些数据传递给javascript。我只想要数组中对象的某些属性。
json gem 似乎不支持 :only
选项。我尝试使用 ActiveSupport::JSON
<script>
test1=<%=raw ActiveSupport::JSON.encode(@sectionDatas.values, :only => [ :left, :width ])%>;
</script>
但忽略 :only
并打印整个对象。
然后我想我会很聪明,从控制器中获取 render 方法:
test2=<%=raw render :json => @sections.as_json(:only => [:left, :width])%>
但我得到了 Nil:Nilclass 错误。
我还尝试将其放入我的模型中并运行 to_json:
include ActiveModel::Serialization::JSON
def attributes
@attributes ||= {'left' => 0, 'width'=>0}
end
同样,这会忽略属性方法并序列化整个对象。
当然,这一定很简单。我缺少什么?
I'm trying to pass some data to javascript in my view. I only want certain attributes of the objects in the array.
The json gem doesn't appear to support the :only
option. I tried to use ActiveSupport::JSON
<script>
test1=<%=raw ActiveSupport::JSON.encode(@sectionDatas.values, :only => [ :left, :width ])%>;
</script>
but that ignores the :only
and prints the whole object.
Then I thought I would be clever and take the render
method from the controller:
test2=<%=raw render :json => @sections.as_json(:only => [:left, :width])%>
but I get Nil:Nilclass errors.
I also tried to put this in my model and run to_json:
include ActiveModel::Serialization::JSON
def attributes
@attributes ||= {'left' => 0, 'width'=>0}
end
Again, this ignores the attributes method and serializes the whole object.
Surely this must be simple. What am I missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
假设数组中的对象是
ActiveRecord::Base
的实例或包含ActiveModel::Serialization::JSON
:Assuming the objects in the array are instances of
ActiveRecord::Base
or includeActiveModel::Serialization::JSON
:当您使用
select
从数据库获取对象时,您可以过滤掉不需要的列。当然,这不是Rails3的方式。这里是:
更新
如果您想要原始的对象数组和 json 但带有过滤属性的 json,您将需要覆盖 to_json:
此 帖子解释了如何做到这一点:
如何在Rails中覆盖to_json?
You can filter out the columns you don't need when you get objects from the db with
select
.Of course, this is not the Rails3 way. Here that is:
Update
If you want to have the original array of objects and json but the json with filtered attributes you will need to override to_json:
This post explains how to do that:
How to override to_json in Rails?