ryandawkins
ryandawkins

Reputation: 1545

Auto joining relations in ActiveRecord

Hello I've created a base REST Controller for my Rails application and I am struggling to get my ActiveRecord models to join for requests.

My goal is to accomplish something like this:

Request: GET /appointment Response:

[
    {
        "id":1,
        "customer_id":3,
        "customer":{
            "name":"John Doe"
        },
        "date":"2011-11-11T00:00:00.000Z",
        "created_at":null,
        "updated_at":null,
        "employee_id":1,
        "employee":{
            "name":"Jane Doe"
        }
    }
]

However I am just getting this:

[
    {
        "id":1,
        "customer_id":3,
        "date":"2011-11-11T00:00:00.000Z",
        "created_at":null,
        "updated_at":null,
        "employee_id":1
    }
]

Here's my base REST Controller: http://pastebin.com/gQqBNeCH You can read the entire thing if you want, otherwise you can just read the code I'm focusing on:

def index
  @objects = get_class().all

  @objects.each do |x|
    x.get_relations
  end

  render json: @objects
end

Here's my Appointment model

class Appointment < ActiveRecord::Base

  belongs_to :customer
  belongs_to :employee

  attr_accessor :customer

  validates :customer_id, presence: true, :numericality => {
    :only_integer => true,
    :allow_blank => false,
    :greater_than => 0
    }

  validates :employee_id, :numericality => {
    :only_integer => true,
    :allow_blank => false,
    :greater_than => 0
    }

  validates :date, presence: true

  def get_relations
    @customer = Customer.find(self.customer_id)
  end

end

My original method was just to use a member variable like such:

def get_relations
  @customer = Customer.find(self.customer_id)
end

However it looks like ActiveRecord has some sort of serializer method it runs with render. Any advice of how to attach my belongs_to relations to that object?

Upvotes: 0

Views: 527

Answers (2)

Marc Lainez
Marc Lainez

Reputation: 3080

If you want to change the way AR renders objects to json, you can override the as_json method (http://apidock.com/rails/ActiveModel/Serializers/JSON/as_json) in your model. But that would mean putting presentation information within your model which I'm not a big fan of.

You can also include the relation in your to_json call:

render :json => @objects.to_json(:include => :relation)

But in your case, as you're building an api I would look into some more advanced JSON formatting options such RABL or JBuilder

Upvotes: 2

usha
usha

Reputation: 29349

You will have to include it in your json response explicitly

def index
  @objects = get_class().all
  render json: @objects.to_json(:include => [:employee, :company])
end

Upvotes: 0

Related Questions