【问题标题】:Rails 3: Rendering certain attributes of an array of objects in JSONRails 3:在 JSON 中呈现对象数组的某些属性
【发布时间】:2011-07-20 01:22:20
【问题描述】:

在我看来,我正在尝试将一些数据传递给 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

同样,这会忽略属性方法并序列化整个对象。

当然,这一定很简单。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 json


    【解决方案1】:

    假设数组中的对象是ActiveRecord::Base 的实例或包含ActiveModel::Serialization::JSON

    test2=<%=raw @sections.to_json(:only => [:left, :width]) %> 
    

    【讨论】:

      【解决方案2】:

      使用select从数据库中获取对象时,可以过滤掉不需要的列。

      Item.find( :all, :select => 'DISTINCT fieldname' )
      

      当然,这不是 Rails3 的方式。这里是:

      Model.select(attribute)
      

      更新

      如果你想要原始的对象和 json 数组,但是带有过滤属性的 json,你需要覆盖 to_json:

      post 解释了如何做到这一点:

      How to override to_json in Rails?

      【讨论】:

      • 这不会导致额外查询数据库以获取我已有的数据吗?
      • 我假设你会用我建议的代码替换它。
      • 是的,但我也需要完整的对象,看不到对我已经拥有的数据进行额外查询的用途。另外我在 .select 上找不到任何文档,它是 ActiveRecord 的一部分吗?
      • 你需要在你的模型中覆盖 to_json 。检查更新。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 1970-01-01
      • 2019-04-28
      • 2011-07-06
      • 2018-06-02
      相关资源
      最近更新 更多