Adam12344
Adam12344

Reputation: 1053

Getting attributes from model in json format - Rails

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'?

Upvotes: 1

Views: 1197

Answers (2)

Sergey Moiseev
Sergey Moiseev

Reputation: 2963

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.

Upvotes: 1

jhack
jhack

Reputation: 81

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

Upvotes: 2

Related Questions