ruby - active model serializer with virtual attribute - Rails 4 -
i making api ror, , need create object virtual attributes , associated object.
the problem serializer not kick in when return object virtual attribute.
here returned object foo_controller
{ :id=>280, :virtual=>"y8st07ef7u" :user_id=>280 }
:virtual virtual attribute , user_id id of associated table - user.
my goal make this
{ :id=>280, :virtual=>"y8st07ef7u", :user=>{ :id=>280, :name=>'foo' } }
foo_controller setting
class api::v1::fooscontroller < applicationcontroller foos = foo.all foos.each |foo| foo.set_attribute('y8st07ef7u') end render json: foos.to_json(:methods => :virtual), status: 200 end
foo_model setting
class foo < activerecord::base belongs_to :user attr_accessor:virtual def set_attribute(path) self.virtual = path end end
foo_serializer setting
class fooserializer < activemodel::serializer attributes :id, :virtual has_one :user end
foo migration setting
class createfoos < activerecord::migration def change create_table :foo |t| t.references :user end end end
user model
class user < activerecord::base has_many :foos end
user serializer
class userserializer < activemodel::serializer attributes :id, :name belongs_to :foo end
when replace "foo.to_json(:methods => :virtual)" in foo_controller "foos", serializer kicks in , user object inside returned json instead of user_id, :virtual not in json.
are there ways can object both virtual attributes , associated object using active model serializer.
thank in advance help!
i figured out. simple.
i had add ":virtual" attributes in foo_serializer , replace "foo.to_json(:methods =>:virtual)" "foos"
Comments
Post a Comment