Rails 3: rendering specific attributes of an array of objects in JSON

I am trying to pass some data to javascript in my opinion. I need only certain attributes of the objects in the array.

The json driver does not support the :only option. I tried using ActiveSupport :: JSON

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

but ignores :only and prints the entire object.

Then I thought that I would be smart 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 putting this in my model and running to_json:

 include ActiveModel::Serialization::JSON def attributes @attributes ||= {'left' => 0, 'width'=>0} end 

Again, this ignores the attribute method and serializes the entire object.

Of course, this should be simple. What am I missing?

+4
source share
2 answers

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

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

Of course, this is not Rails3. That's what:

 Model.select(attribute) 

Update

If you want to have the original array of objects and json, but json with filtered attributes, you need to override to_json:

This post explains how to do this:

How to override to_json in Rails?

+2
source

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

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

Source: https://habr.com/ru/post/1344691/


All Articles