- ruby 1.9.2p290
- rails 3.1.1
Basically I have two models: CHEFS and RECIPES.
class Chef < ActiveRecord::Base
has_many :recipes
end
class Recipe < ActiveRecord::Base
belongs_to :chef
end
And the following routes:
resources :recipes
resources :chefs do
# list of recipes from chef
resources :recipes, :to => 'recipes#index_chef'
end
With this I have the urls (exactly what I want):
- /recipes – list of recipes
- /chefs/username/recipes – list of chef’s recipes
- /chefs/ – list of chefs
- /chefs/username – chef’s profile
RecipesController:
def index
@chef = Chef.find_by_username(params[:chef_id])
@recipes = Recipe.where({ :status_id => 1 }).order("id desc").page(params[:page]).per(9)
end
def index_chef
@chef = Chef.find_by_username(params[:chef_id])
@recipes = @chef.recipes.where(:status_id => 1).order("id desc").page(params[:page]).per(9)
end
My recipes index view:
<%= link_to recipe.chef.username.capitalize, @chef %>
In http://3001/chefs/username/recipes I have the correct link to Chef profile.
But in http://3001/recipes I have the wrong link.
What am I doing wrong?
In http://3001/recipes (which is a weird url!), you don’t have access to
params[:chef_id]. So you won’t have the @chef variable available to you in the view. It should benil!To get around this, change your link_to to this
You might want to eager load the chef to your
@recipesrecords by loading that in your controller like this:Hope this helps.