13671

Tableless model JSON serialization in Rails

Question:

I have tableless model (like it was shown in #219 railscast):

class MyModel include ActiveModel::Conversion extend ActiveModel::Naming attr_accessor :attr1, :attr2, :attr3, :attr4 private def initialize(attr1 = nil) self.attr1 = attr1 end def persisted? false end end

Then I'm trying to render JSON in controller:

@my_model = MyModel.new render json: @my_model.to_json(only: [:attr1, :attr2])

but it renders JSON with all the attributes of the model.

I've tried to add

include ActiveModel::Serialization

but it didn't change rendered JSON.

How can I render JSON with only necessary attributes of my tableless model?

I'm using Rails 3.2.3

<strong>Update</strong>

Thanks, guys. It seems you're all almost right. I combined your solutions and got this:

Model:

include ActiveModel::Serialization ... def to_hash { attr1: self.attr1, attr2: self.attr2, ... } end

Controller:

render json: @my_model.to_hash.to_json(only: [:attr1, :attr2])

I really don't know whose answer to be accepted.

<strong>Update 2</strong>

Suddenly new strangeness appeared. One of the attributes is array of hashes. It was like this:

attr1: [[{name: "name", image: "image"}, {name: "name", image: "image"}], [{name: "name", image: "image"}, {name: "name", image: "image"}]]

But now it lost all its content and looks like this:

attr1: [[{}, {}], [{}, {}]]

Maybe anyone know how to fix it?

<strong>Update 3</strong> :)

Erez Rabih's answer helped. Using slice instead of to_json solved the problem. So, final solution is:

render json: @my_model.to_hash.slice(:attr1, :attr2)

Answer1:

I know it isn't straight forward but how about:

render :json => @my_model.attributes.slice(:attr1, :attr2)

You will also be required to define an attributes method as:

def attributes {:attr1 => self.attr1.....} end

Thanks for the comment bender.

Answer2:

I believe it's because Object::as_json is calling internally (look at this: <a href="http://apidock.com/rails/Object/as_json" rel="nofollow">http://apidock.com/rails/Object/as_json</a>), and it has no options like :only or :except, so you can overide method to_hash in your class, e.g.:

def to_hash {:attr1 => self.attr1, :attr2 => self.attr2} end

and to_json will do exactly what you want.

Certainly, another option is to override method to_json ...

Answer3:

You may mix your initial approach (including AM serialization modules) with Erez' one as the <a href="http://api.rubyonrails.org/classes/ActiveModel/Serialization.html" rel="nofollow">documentation</a> suggests.

class MyModel include ActiveModel::Serialization::JSON .... def attributes {:attr1 => self.attr1.....} end ... end

Recommend

  • Can't build project using mongodb c++ driver with MSVC
  • How to get url of Active Storage image
  • How to truncate data in a hash so that the resulting JSON isn't longer than n bytes?
  • When is InputStream.available() useful?
  • Work around for HTML stripping quotes in quirks mode?
  • How to trick Node.js to load .js files as ES6 modules?
  • API (curl)Command to Approve a promoted build Job in Jenkins
  • Firefox augments the content-type of XMLHttpRequest
  • JSON data through JS/AJAX into PHP
  • Sails.js API passport.js authentication
  • Grunt watch Running “watch” task Waiting
  • How to check if DIV element is disabled using jquery
  • Can you use DataSet and DataTables in a Portable Class Library
  • Laravel lmutator $this->attributes return 'Undefined index: id'
  • CSS Grid, position absolute an element in a css grid item: IMPOSSIBLE
  • How do I change the kernel/python version for iPython?
  • (Play 2.5) How do you define json format for type alias of an Option?
  • How do I bind multiple properties in an Android layout element
  • Unzip archive in .Net CORE 1.0
  • Telegram bot API - Inline bot getting Error 400 while trying to answer inline query
  • Select value from xtype selection type checkbox CQ5
  • how to get data attributes of dynamically generated element
  • Javascript CORS - No 'Access-Control-Allow-Origin' header is present
  • Exception creating JSON with LINQ
  • Angular2 Response for preflight is invalid (redirect) from some GET requests
  • ListItem.Attributes.Add not working
  • Detect when Facebook like button is clicked
  • How to change the font size of a single index for UISegmentedControl?
  • chrome.tabs.executeScript only fires when the Developer Console is open
  • Play WS (2.2.1): post/put large request
  • Different response to non-authenticated users and AJAX calls
  • Warning: Can't call setState (or forceUpdate) on an unmounted component
  • Calling of Constructors in a Java
  • Traverse Array and Display in markup
  • bootstrap to use multiple ng-app
  • Transpose CSV data with awk (pivot transformation)
  • Why can't I rebase on to an ancestor of source changesets if on a different branch?
  • Is it possible to post an object from jquery to bottle.py?
  • Binding checkboxes to object values in AngularJs
  • How to load view controller without button in storyboard?