2012-11-06 26 views
0

在這之前,我已經做了幾個文章,關於如何添加一個喜歡的食譜給用戶..我有一個應用程序,您可以在登錄後上傳食譜,用戶可以搜索整個所有食譜的表格和查看他們自己的食譜在一個會員區..該模型的參數沒有被退回rails 3

現在我希望用戶能夠保存他們最喜歡的食譜,到目前爲止,我可以保存一個喜歡的食譜,因此,我得到的輸出是

[#<Favourite id: 1, user_id: 8, recipe_id: nil, created_at: "2012-11-06 19:25:34", updated_at: "2012-11-06 19:25:34">, 

所以我得到了正確的user_id但沒有params的實際配方,即菜的名稱,原產國。

我的模型,像這樣

用戶

class User < ActiveRecord::Base 

has_many :recipes 
has_many :favourites 

配方

has_many :ingredients 
has_many :preperations 
has_many :favourites 

收藏

belongs_to :user 
belongs_to :recipe 

我favouri TE控制器看起來像這樣

def create 

@favourite = current_user.favourites.new(params[:recipe]) 
if @favourite.save 
redirect_to my_recipes_path, :notice => "Recipe added to Favourites" 
end 
end 

添加到您的收藏夾鏈接

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

我希望我沒有錯過什麼了,任何幫助讚賞

回答

1

如說

<%= link_to "Add to favorites", favorite_path(:recipe_id => @recipe.id), {:method => :post } %> 

但是,這一切都取決於@recipe被定義爲您的控制器 - 例如,如果你有

@recipes = Recipie.all 

並在視圖你有

@recipes.all do |recipe| 

然後在你的鏈接(塊內)你需要有:

<%= link_to "Add to favorites", favorite_path(:recipe_id => recipe.id), {:method => :post } %> 

這有幫助嗎?

3

您需要在鏈接中添加額外的信息,修改創建動作

# View 
<%= link_to "Add to favorites", favorite_path(:recipe_id => @recipe.id), {:method => :post } %> 

# Controller 
def create 
    @favourite = current_user.favourites.new(recipe_id: params[:recipe_id) 
    if @favourite.save 
    redirect_to my_recipes_path, :notice => "Recipe added to Favourites" 
    end 
end 

問題是你沒有發送任何東西Ø在參數params[:recipe]

注意控制器:記得attr_accessible :user_id, :recipe_idFavorite模型。

+0

謝謝你的回答,也嘗試過你的方法,得到錯誤消息調用id爲零,這將錯誤地爲4 - 如果你真的想要的ID爲零,使用object_id – Richlewis

1

您不會通過鏈接發送任何參數。

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

這還不足以將食譜添加到收藏夾。什麼你需要做的是通過配方的ID與此鏈接一起:

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

或者你可以通過使用路由幫助使這個更短:

<%= link_to "Add to favorites", add_to_favorites_path(:recipe_id => recipe), {:method => :post } %> 

定義裏面路由幫手您config/routes.rb這樣的:

post '/favorites' => "favorites#create", :as => "add_to_favorites" 

然後,只需找到params[:recipe_id]控制器內的配方和你需要用它做什麼。

+0

非常感謝你指出,現在雖然當我試圖查看my_recipes頁面時,我得到了未定義的局部變量或方法'recipe',但我選擇了1 – Richlewis

+0

哇,剛纔意識到你是Ryan Bigg誰寫了rails 3的行動中,那本書是我的購買清單中的下一個: ) – Richlewis

+0

道歉,好像我的問題不在現場,現在問題已解決 – Richlewis