link_to action "mostrar" a otro controlador

  • rubí 1.9.2p290
  • rieles 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):

  • /recetas - lista de recetas
  • /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

Mis recetas índice ver:

<%= link_to recipe.chef.username.capitalize, @chef %>

In http://3001/chefs/username/recipes I have the correct link to Chef profile.

Pero en http://3001/recipes I have the wrong link.

¿Qué estoy haciendo mal?

preguntado el 09 de marzo de 12 a las 14:03

you don't specify what the intended outcome is or what the current result is. -

Sorry, maybe I didn't explain correctly (my english is not so good). I want the link_to to Chef's show action (/chefs/username) in index view of Recipe's controller. -

1 Respuestas

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 be nil!

To get around this, change your link_to to this

<%= link_to recipe.chef.username.capitalize, recipe.chef %>

You might want to eager load the chef to your @recipes records by loading that in your controller like this:

 @recipes = Recipe.where({ :status_id => 1 }).includes(:chef).order("id desc").page(params[:page]).per(9)

Espero que esto ayude.

respondido 09 mar '12, 15:03

Phyo, thank you very much! Works nicely. The eager loading hint too. I'm new on rails! Why did you think that url is weird? - maiconsanson

Usually it's like 127.0.0.1:3001/recipes or localhost:3001/recetas etc. Maybe you have changed your host file ? - Gana Phyo Wai

Sure, you are right. For some reason I omitted the localhost: - maiconsanson

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.