Rails 3:在JSON中渲染对象数组的某些属性

时间:2021-03-13 13:26:14

I'm trying to pass some data to javascript in my view. I only want certain attributes of the objects in the array.

我想在我的视图中将一些数据传递给javascript。我只想要数组中对象的某些属性。

The json gem doesn't appear to support the :only option. I tried to use ActiveSupport::JSON

json gem似乎不支持:only选项。我尝试使用ActiveSupport :: JSON

<script>
test1=<%=raw ActiveSupport::JSON.encode(@sectionDatas.values, :only => [ :left, :width ])%>;
</script>

but that ignores the :only and prints the whole object.

但是忽略了:only并打印整个对象。

Then I thought I would be clever and take the render method from the controller:

然后我想我会很聪明并从控制器中获取render方法:

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

but I get Nil:Nilclass errors.

但我得到Nil:Nilclass错误。

I also tried to put this in my model and run to_json:

我也尝试将它放在我的模型中并运行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?

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

2 个解决方案

#1


2  

You can filter out the columns you don't need when you get objects from the db with select.

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

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

Of course, this is not the Rails3 way. Here that is:

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

Model.select(attribute)

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:

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

This post explains how to do that:

这篇文章解释了如何做到这一点:

How to override to_json in Rails?

如何在Rails中覆盖to_json?

#2


3  

Assuming the objects in the array are instances of ActiveRecord::Base or include ActiveModel::Serialization::JSON:

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

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

#1


2  

You can filter out the columns you don't need when you get objects from the db with select.

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

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

Of course, this is not the Rails3 way. Here that is:

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

Model.select(attribute)

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:

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

This post explains how to do that:

这篇文章解释了如何做到这一点:

How to override to_json in Rails?

如何在Rails中覆盖to_json?

#2


3  

Assuming the objects in the array are instances of ActiveRecord::Base or include ActiveModel::Serialization::JSON:

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

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