A custom model method that should be included in JSON serialization

I work with javascript library where I create comboboxes. I have a requirement to create a combo box with the full name of the person, so I mean the name + surname.

Since there are two separate fields in the database (and in my model too), I would like to know if there is a quick way (instead of manually creating all the hash objects) to "simulate" the presence of an additional field in my model for conversion JSON because this object must be returned as a JSON array in which you can read * full_name * as a key.

thanks for the help

+4
source share
3 answers

You can overwrite the to_json method in your model by passing :methods parameters and calling super . This will call the as_json version of the superclass with the parameters :methods so that it serializes your model with full_name attributes.

 class Person < ActiveRecord::Base def as_json(options={}) options[:methods] = [:full_name] super end def full_name "#{first_name} #{last_name}" end end 

Inside your controller, you can simply

 render :json => @person 

Check out this document if you want to know more parameters that can go to the as_json method. http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

+8
source

This seems to be a duplicate of this question:

Rails 3 reply_to json with custom attributes / methods

In particular: hash method:

 respond_with({ :cars => @cars.as_json(:only => [:make, :model], :methods => [:full_name]), :vans => @vans }) 
+1
source

What you can do is setter method in your User class

 def full_name=(string) names = string.split # the default delimiter is a space self.update_attributes(:first_name => names[0], :last_name => names[1]) end 

Then the form should refer to :full_name as a field, and even if it is not an actual column, Rails will automatically get access to the above method and execute it, thereby updating the necessary columns.

-1
source

Source: https://habr.com/ru/post/1415215/


All Articles