I'm using Couchrest_model as a Rails ORM to CouchDB. I want to have Rails do a "join" of information from two different CouchDB documents for a view, but can't seem to get Rails to auto-retrieve the joined data.
Here's the two related models:
class Package < CouchRest::Model::Base
belongs_to :vendor
property :shortcode, String
property :pins, Integer
end
class Vendor < CouchRest::Model::Base
property :vendor, String
timestamps!
end
So, now in my index.html.erb for /packages I want to display a table with the data from my two models:
<h1>Listing packages</h1>
<table>
<tr>
<th>Shortcode</th>
<th>Pins</th>
<th>Vendor</th>
<th></th>
</tr>
<% @packages.each do |package| %>
<tr>
<td><%= package.shortcode %></td>
<td><%= package.pins %></td>
<td><%= package.vendor %></td>
<td><%= link_to 'Show', package %></td>
<td><%= link_to 'Edit', edit_package_path(package) %></td>
<td><%= link_to 'Destroy', package, confirm: 'Are you sure?', method: :delete %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Package', new_package_path %>
I want to display the vendor string from the Vendor model. I've used a selector helper in a view to display "joined" information across models with CouchDB, but I can't figure out how to join in this seemingly simpler case of just printing the string in the view table.
Here's the Package controller that corresponds to the index, which is pretty standard:
class PackagesController < ApplicationController
# GET /packages
# GET /packages.json
def index
@packages = Package.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @packages }
end
end
I've tried doing the standard
@packages = Package.all(:include => :vendor)
but Couchrest_model doesn't pull in the vendor information that way...
I am not sure if I understand your question, but you want to get the vendor string from the instance of Vendor which is attached to your package instance? Just use @package.vendor.vendor
There is no (easy) way to include the vendor record while fetching all packages, so that you only have to make 1 request. You have to fetch the vendor after you fetched all packages because CouchDD does not support document linking or joins. If you have for example 100 packages and want to fetch the vendor string from all attached vendors you end up with a typical n+1 situation (100+1 requests). 1 request to fetch all packages and 100 for each vendor. A better solution is to get all keys of all vendors after the first request and fetch all vendors in a second request using the "keys" parameter while fetching. (Documentation)
I hope i could help you.