开发者

Rails 3: Rendering certain attributes of an array of objects in JSON

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 attr开发者_运维知识库ibutes
  @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?


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

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


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

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

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

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:

This post explains how to do that:

How to override to_json in Rails?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜