0

Im just looking for some clarification on the following piece of code, well part of it.To give some background i have an app where you can upload recipes, search recipes and save them as favourites, this piece of code is in a controller "recipes", action is "my_recipes"

<%= link_to "Add to favorites",  {:controller => 'favourites', :action => 'create', :recipe_id => recipe.id}, {:method => :post } %>

My understanding is that this creates a link_to (anchor tag if you will) that makes a post request through the create method within the favourites controller. This part I think i underdstand (corrections welcome), the part i am unsure of is

:recipe_id => recipe.id}

I know this is passing the recipe_id for example but I would like to know why we do this? and what relevance of the : before the first recipe_id.May seem obvious to some but you dont know until you learn.

Any help appreciated

Thilo
  • 17,565
  • 5
  • 68
  • 84
Richlewis
  • 15,070
  • 37
  • 122
  • 283
  • Are you in index page of recipe?, if so, in your create action of favorites controller, you can find recipe is favorited by: `@favorite = Recipe.find(params[:id]` and don't need `:recipe_id => recipe.id` – Thanh Nov 07 '12 at 09:48
  • "but I would like to know why we do this"... We don't know what the application does, so there is no way to answer this question. It *seems* this link is adding a recipe to a list of favorites. To be able to add a recipe to a list of favorites you need the `id` of the recipe. That's probably why it is being passed. – Mischa Nov 07 '12 at 09:48
  • apologies, should have been a little clearer with my question, have updated – Richlewis Nov 07 '12 at 09:53
  • The `:` makes `:recipe_id` a symbol. See http://stackoverflow.com/questions/2341837/understanding-symbols-in-ruby. – Thilo Nov 07 '12 at 18:11

1 Answers1

1

Is this code in a partial? Is recipe being passed along? You should rewrite as so:

link_to "Add to favorites",  new_favourite_path(recipe), method: :post

Do rake routes in your console and find out what the path is for creating favourites, then replace 'new_favourite' with that above. Note, the route might be identified with something more explicit like new_favourite_recipe.

To answer you question, you must pass recipe, or recipe.id because otherwise the controller wouldn't know which recipe to add to the favourites. You don't need to specify the user as that should be accessed directly from within the controller action using something like current_user.

Damien Roche
  • 13,189
  • 18
  • 68
  • 96