Hommer Smith
Hommer Smith

Reputation: 27852

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.

Upvotes: 0

Views: 190

Answers (2)

Nobita
Nobita

Reputation: 23713

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

Upvotes: 3

Shadwell
Shadwell

Reputation: 34774

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.

Upvotes: 0

Related Questions