views:

27

answers:

2

Is it possible to display a belongs_to relationship in a single jqgrid?

Example:

Vehicle belongs to Person

I can display the Vehicle jqgrid listing the person_id, but I would like to display the Person's name instead of their id.

Example:

person_id|vehicle_type
    1    |    honda 


person_name|vehicle_type
    Tom    |    honda

EDIT (Vehicle controller code):

class VehiclesController < ApplicationController

  def index
    @vehicles = Vehicle.find(:all) {
      if params[:page].present? then
        paginate :page => params[:page], :per_page => params[:rows]
        order_by "#{params[:sidx]} #{params[:sord]}"
      end
    }

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @vehicles }
      format.json  { render :json => @vehicles }
      format.jgrid {
        render :json => @vehicles.to_jqgrid_json(
          [:person_id, :vehicle_type],
          params[:page],
          params[:rows],
          @vehicles.total_entries
        )
      }
    end
  end
end
A: 

You need to express this relationship server-side, for example by joining the tables together (although IIRC there are more elegant ways to do this in Rails):

    SELECT p.person_name, v.vehicle_type
      FROM vehicle v
INNER JOIN person p ON p.person_id = v.person_id

Then just make sure to include person_name in your jqgrid's colmodel.

Justin Ethier
+1  A: 

I found a solution without modifying the query. In the attributes, using "person.name" will use the Person's name that belongs to the vehicle.

render :json => @vehicles.to_jqgrid_json(
          ["person.name", :vehicle_type],
          params[:page],
          params[:rows],
          @vehicles.total_entries
        )
Trevor