PDA

View Full Version : Lazy loading association & RESTful Rails



atwoodjw
14 Apr 2011, 8:19 PM
I'm trying to get a hasMany association to lazy load the appropriate records from my RESTful Rails back-end. So really, this is more of a Ruby question. But hopefully its helpful to others.

I have 2 models... Class & Student.


Ext.regModel("Class", {
hasMany: {
model: 'Student',
name: 'students'
}
...
}

Ext.regModel("Student", {
belongsTo: 'Class'
...
}


When I tap a class, I load the students for that class.


initComponent: function () {
var myClass = Ext.StoreMgr.lookup('Class').findRecord('id', 3680);
this.store = myClass.students().load();

...
}


This calls the back-end with the following URL.


localhost:3000/students.json?filter=[{"property":"class_id","value":3680}]


What is the best way to apply this filter to the ARel query for Students? Here's what I have so far. It works, but it's ugly and brittle. How can I improve it? Extend it to support sorting, limits, and other fun things?



class StudentsController < ApplicationController
def index
filter_params = HashWithIndifferentAccess.new

if (params[:filter])
filter = ActiveSupport::JSON.decode(params[:filter])
filter_params[filter[0].values[0]] = filter[0].values[1]
end

@students = Student.where(:class_id => filter_params[:class_id])

...
end
end