0

I am querying my ActiveRecords in rails with the following:

result = MyObj.where({customer: current_id}).as_json()

There are two columns returned:

result = [{id:1, name: "david", last_name: "Smith:"}]

I would like create a third column (which will not be saved to the DB) like so:

result = [{id:1, name: "David", last_name: "Smith:", full_name:"David Smith"}]

Is this possible within the WHERE query?

0

3 Answers 3

2

Add a full_name method to your MyObj model, then pass methods: :full_name to the as_json method:

class MyObj
  def full_name
    "{name} #{last_name}"
  end
end

result = MyObj.where({customer: current_id}).as_json(methods: :full_name)

From the documentation for as_json:

To include the result of some method calls on the model use :methods:

user.as_json(methods: :permalink)
# => { "id" => 1, "name" => "Konata Izumi", "age" => 16,
#      "created_at" => "2006/08/01", "awesome" => true,
#      "permalink" => "1-konata-izumi" }

Or alternately, you could override as_json on the model to include full_name by default:

class MyObj
  def full_name
    "{name} #{last_name}"
  end

  def as_json(options={})
    super({methods: :full_name}.merge options)
  end
end
Sign up to request clarification or add additional context in comments.

Comments

1

Sure. Override the method in your model...

class MyObj < ActiveRecord::Base

  def full_name
    "#{name} #{last_name}"
  end

  def as_json options={}
    {
      id: id,
      name: name,
      last_name: last_name,
      full_name: full_name
    }
  end
end

Comments

0

Quick and dirty just manipulate the results you get back

result = MyObj.where({customer: current_id})
result.map{|customer| "full_name: #{customer.first_name + customer.last_name}" }

But be careful of nil values.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.