Ruby on rails 没有方法错误问题

Ruby on rails 没有方法错误问题,ruby-on-rails,ruby,rails-activerecord,Ruby On Rails,Ruby,Rails Activerecord,我是一名新的rails开发人员,有一个基本的脚手架crud应用程序,我对其进行了一些修改 我得到了这个错误: 未定义的方法说明# 当我访问john/recipes/46时。以下是我的看法: <h1 itemprop="name"><%= @recipe.name %></h1> <ul> <li><%= link_to 'Edit', edit_recipe_path(@recipe) %></l

我是一名新的rails开发人员,有一个基本的脚手架crud应用程序,我对其进行了一些修改

我得到了这个错误:

未定义的方法说明#

当我访问
john/recipes/46
时。以下是我的看法:

<h1 itemprop="name"><%= @recipe.name %></h1>
<ul>        
   <li><%= link_to 'Edit', edit_recipe_path(@recipe) %></li>
</ul>
<p itemprop="description"><%= @recipe.description %></p>
以下是我的节目索引:

def show
 @user = User.find_by_username params[:username]
 @recipe = Recipe.where(:user_recipe_id => params[:id])

 respond_to do |format|
  format.html # show.html.erb
  format.json { render json: @recipe }
 end
end
我的模型是:

before_save :set_next_user_recipe_id

belongs_to :users

validates :user_recipe_id, :uniqueness => {:scope => :user_id}

def to_param
  self.user_recipe_id.to_s
end

def set_next_user_recipe_id
  self.user_recipe_id ||= get_new_user_recipe_id
end

def get_new_user_recipe_id
  user = self.user
  max = user.recipes.maximum('user_recipe_id') || 0
  max + 1
end

attr_accessible :description, :duration, :author, :url, :name, :yield, :ingredients_attributes, :user_recipe_id, :directions_attributes, :tag_list, :image
我之所以要做一个
Recipe.where(:user\u Recipe\u id=>params[:id])
而不是
Recipe.where(:id=>params[:id])
是因为我试图这样做,而不是
john/recipes/46
在数据库中显示第46个配方,而是显示属于john的第46个配方


谢谢你的帮助

您只尝试查找一个配方,但您的查询正在搜索多个配方。当您使用一个普通的
,其中(…)
而不以
结尾时,Rails首先将其解释为“使用此用户id向我显示所有(多个)配方”,而不是“使用此id向我显示(一个)配方”

因此,您需要将
。放在查询末尾的第一个

@recipe = Recipe.where(:user_recipe_id => params[:id]).first
或者使用只返回一条记录的ActiveRecord finder:

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

谢谢你的回复。不幸的是,当我这样做时,我得到了nil:NilClass的
未定义的方法名?
这是什么原因?这意味着没有提供
user\u recipe\u id
的配方。请将您的关联表改为:user。当您想使用@recipe.user.name显示名称recipe时。
@recipe = Recipe.find_by_user_recipe_id(params[:id])