Home>

We are currently creating a favorite registration function.

The existing tables are as follows. (Since the text will be long, we will assume that the association is organized correctly.)

・ User table
・ Nutrition table * Ingredients
-Favorite table (intermediate table * columns are user_id and nutrition_id)

If there is a food that the user likes, I would like to save the current_user.id and the id of the corresponding nutrition in the Favorite table by pressing the registration button, but ... Although the parameters can be passed, the "Nutrition ID" is I'm in a state where I've been told "No!" ...

[Displayed error]
ActiveRecord :: RecordNotFound in FavoritesController # create
Couldn't find Nutrition without an ID

----------- The following code ---------------

[View] index.html.erb
Omission
<% if! Favorite.exists? (User_id: current_user.id, nutrition_id: nutrition.id)%>
<% = link_to "favorites", user_favorites_path (user_id: current_user.id, nutrition_id: nutrition.id), method :: post%>
<% else%>
<% = link_to "Unfavorite", favorite_path (current_user.id, nutrition.id), method:: delete%>
<% end%>
Omission

[Routing] routes.rb
Omission
resources: users do
resources: favorites, only: [: show,: create,: destroy] ← The action used this time is create
end
Omission

[Controller] favorites_controller.rb
Omission
def create
@user_id = session [: id]
@nutrition_id = Nutrition.find (params [: id]). id ← Error occurred here
@favorite = Favorite.new (nutrition_id: @nutrition_id, user_id: @user_id)
if @ favorite.save
redirect_to user_favorite_path (session [: id])
end
end

Omission

def favorite_params
params.require (: favorite) .permit (: user_id,: nutrition_id)
end

end

――――――――――――――――――――――――――――――――――――――――――――――

I have parameters, but why can't I pass them? (From the error below)
Parameters:
{"_method" =>"post", "authenticity_token" =>"MajNmuaXydwLwBBdnogZfKHJvWddHFCsD9W4InLKU3g9omXjGdPjsl0Bqq8hOZsNC9K/XkyLOH7KjOkzymH/2w ==", "

Thanks for your professor.

  • Answer # 1

    I amnutrition_idHowever, I am referring to it.params [: id]That's why.
    @nutrition_id = params [: nutrition_id]To.
    You don't have to "finde with id and take that id".