1

I would like to pull all attributes except for a few out of a model, and convert the data to json format.

A class I defined in my model:

mdl.rb

class Mdl< ActiveRecord::Base
    def self.get_json
        self.all.pluck(:a, :b, :c).to_json
    end
end

This returns:

[[0.0,1.0,365.0]]

I have 2 questions:

1) How can I have the json return with attribute names? i.e. [a: 0.0, b: 1.0, c: 365.0]

2) Is there a way to pull the attributes based on 'all columns except x, y, & z'?

2 Answers 2

2

1) Instead of doing a self.all.pluck, try self.all.to_json or self.all.as_json this will give you the attribute names like you wanted.

2) You can use select, for example:

self.all.select(:a, :b, :c)

That should work

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Using this I am now getting an id: null with my other attributes, is there a way to remove that? [{"id":null,"a":1.0,b:1.0,c:365.0}]
Do you want to completely get rid of id? or have the id value as well? If you want the id value, you could add the id to your select.
1

Common approach currently is to use ActiveModelSerializers gem for that. It'll allow you to manage your json serialization same way as you manage your views. So first serializer using that will be like this:

class MdlSerializer < ActiveModel::Serializer
  attributes :a, :b, :c
end

and you will be able to render it to json with automatic serializer lookup like this:

render json: @mdl

ActiveModelSerializers is de-facto standard for Rails 5, and works well in Rails 4.

2 Comments

Reading up on this, thanks. Is this what I would use if I created an API, or does rails-api use something else?
Rails-api authors recommend using AMS.

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.