4

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?

2 Answers 2

3

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

test2=<%=raw @sections.to_json(:only => [:left, :width]) %> 
Sign up to request clarification or add additional context in comments.

Comments

2

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?

4 Comments

Won't that cause an extra query to the database for data I already have?
I was assuming that you would replace the it with the code I suggested.
Yep but I need the full object too, don't see the use in doing an extra query for data I already have. Also I can't find any docs on .select, is it part of ActiveRecord?
you need to override to_json in your model then. Check the update.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.