Tableless model JSON serialization in Rails -


i have tableless model (like 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 render json in controller:

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

but renders json attributes of model.

i've tried add

include activemodel::serialization 

but didn't change rendered json.

how can render json necessary attributes of tableless model?

i'm using rails 3.2.3

update

thanks, guys. seems you're right. combined solutions , 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 don't know answer accepted.

update 2

suddenly new strangeness appeared. 1 of attributes array of hashes. this:

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

but lost content , looks this:

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

maybe know how fix it?

update 3 :)

erez rabih's answer helped. using slice instead of to_json solved problem. so, final solution is:

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

i know isn't straight forward how about:

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

you required define attributes method as:

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

thanks comment bender.


Comments

Popular posts from this blog

javascript - backbone.js Collection.add() doesn't `construct` (`initialize`) an object -

php - Get uncommon values from two or more arrays -

Adding duplicate array rows in Php -