简体   繁体   中英

Using a method result in as_json

Right now I have the following in my as_json method in a model:

  #values we will pass to Json
  def as_json(options={})
    super(:only => [:name, :last_name, :age])
  end

I have a method that does some logic and returns a value:

def self.full_name
 self.name + self.last_name
end

How can I return the "options" result in the as_json along with the fields that I already have? I have tried this:

#values we will pass to Json
  def as_json(options={})
    super(:only => [:name, :full_name => self.full_name, :last_name, :age])
  end

With no luck.

Shadwell's answer is completely correct. However, I think that you could just use the :methods key like this:

def as_json(options={})
    super(:only => [:name, :last_name, :age], :methods => [:full_name])
end
def as_json(options = {})
  super(:only => [:name, :last_name, :age]).merge(
    { :full_name => self.full_name }.as_json
  )
end

This uses the default implementation for the model attributes and then merges in your derived attribute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM