我在控制器中的 show 函数找不到对象的创建者



我有一个rails应用程序的一部分,用户将创建一个食谱,该食谱将保存在他们的"食谱"中。其他用户将能够从其他用户那里获取食谱。因此,应用程序中将有一个方面显示谁创建了配方。

配方的架构

create_table "recipes", force: :cascade do |t|
 t.string "recipe_name"
 t.string "description"
 t.integer "calories"
 t.integer "carbs"
 t.integer "fats"
 t.integer "protein"
 t.integer "user_id"
 t.datetime "created_at", null: false
 t.datetime "updated_at", null: false
end

我遇到麻烦的地方是显示食谱的创建者。

  def show
   @user = current_user
   @recipe = Recipe.find_by(params[:id])
   creator = User.find_by(params[@recipe.user_id])
   @creator = creator.first_name
  end

所以现在我有两个用户的约翰(Id:1(和Alex(Id:2(。当我让 Alex 制作食谱并在@recipe下面撬动时,当我调用 @recipe.user_id 时,我得到 2 user_id。

但是,当我将撬子放在创建者下并调用创建者时,我得到了 1 的user_id,我得到了约翰。我相信我试图在@recipe中使用user_id找到用户的方式有问题。我想知道是否有人知道我做错了什么,或者我是否需要添加更多信息。谢谢。

这个:

User.find_by(params[@recipe.user_id])

由于以下几个原因,这没有意义:

  • find_by需要一个类似哈希的结构。像这样:User.find_by(id: xxx)
  • params[@recipe.user_id]没有意义,因为那将是这样的:params[1]这不是你想要的。

这:

@recipe = Recipe.find_by(params[:id])

还患有畸形find_by

因此,请尝试以下操作:

def show
  @user = current_user
  @recipe = Recipe.find(params[:id])
  creator = @recipe.user
  @creator = creator.first_name
end

当然,这假设您正确设置了ReceiptUser之间的关联(即使用 belongs_to (。

最新更新