I am kind of new with backbone.js and i am struggling with fetching a collection with a belong_to relation.
I would like to fetch a list of users (users/ GET) and i would like to display them all but with a belongs_to association.
For example to display the company name of the user. Somebody knows a solution?
I am using Ruby on Rails 3 with CouchDB
def index
User.all
end
class UserCollection extends Backbone.Collection
url: ->
app.routes.users_url
model: User
class User extends Backbone.Model
idAttribute: '_id'
defaults: {
"email": null
"mobile": null
"loc": null
}
url: ->
app.routes.users_url + '/' + (@id || '')
I would like to show the company name like this...
%script{:id => "user-resource-template", :type => "text/template"}
%td= check_box_tag "select", 1, false, :class => "checkbox", "data-id" => raw("<%= _id %>")
%td <%= name %>
%td <%= email %>
%td <%= company.name %>
Backbone.js doesn't seem to support relations, as there is no mention of them in the official documentation.
All is not lost, though, there are some Backbone plugins that add support for relations, such as Backbone-relational or ligament.js. I haven't tested them, but Backbone-relational seems pretty active.
Update
To lazy-load collections and prevent one fetch per relation, see the fetchRelated
method in Backbone.RelationalModel:
Fetch models from the server that were referenced in the model's attributes, but have not been found/created yet. This can be used specifically for lazy-loading scenarios.
By default, a separate request will be fired for each additional model that is to be fetched from the server. However, if your server/API supports it, you can fetch the set of models in one request by specifying a collectionType for the relation you call fetchRelated on. The collectionType should have an overridden url(models) method that allows it to construct a url for an array of models. See the example at the top of Backbone.Relation options or Backbone-tastypie for an example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With