I'm trying to create a new application with both Rails and Backbone.js, but there are quite a few nested relations that are making it rather difficult.
On the Rails side, I'm using a HABTM relationship between Ingredients and Allergens. I'm trying to access the ingredients that are associated with an array of allergens. The plan was to query the Allergens table with the array, get their ids, then query that against the AllergensIngredients table to get the Ingredients ids.
The routes are nested as such:
resources :ingredients do
resources :allergens
end
With the url as '/ingredients/:ingredient_id/allergens'. It works wonderfully for Rails. On the Backbone side I've tried using Collections to fetch the Allergens with the url '/allergens', but that is rejected according to my Rails routes (route '/allergens' does not exist). So, I added a standalone resources :allergens
route underneath my nested routes. That created a recognizable route for Backbone, but issues still remained with my Rails allergens_controller.rb:
class AllergensController < ApplicationController
respond_to :html, :json
def index
respond_with(
@ingredient ||= Ingredient.find(params[:ingredient_id]),
@allergens = @ingredient.allergens,
)
end
# ...
end
because @ingredient cannot be found without an id. I've tried using Backbone.sync and $.get, but those still require a url, which ultimately goes through the rails controller. How can I use Backbone to just query a single table in the database, without any interference from Rails or urls? Thank you so much for your help!