没有方法错误问题rails

时间:2013-07-02 01:28:47

标签: ruby-on-rails ruby rails-activerecord

我是一个新的rails开发人员,他有一个基本的脚手架crud应用程序,我修改了一下。

我收到了这个错误:

undefined method description for #<ActiveRecord::Relation:0x00000102df26d8>

当我访问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>

这是我的路线:

match "/:username" => "recipes#index"
scope ':username' do
  resources :recipes
end

这是我的节目索引:

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_recipe_id => params[:id])而不是Recipe.where(:id => params[:id])的原因是因为我试图这样做而不是john/recipes/46显示数据库中的第46个配方,而是显示属于约翰的第46个食谱。

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

您只是想查找一个食谱,但您的查询正在搜索倍数。当您使用普通where(...)而不是以.first结尾时,Rails将其解释为“使用此用户ID向我显示所有(多个)食谱”而不是“show me < strong> (一个)具有此ID的食谱“。

因此,您需要将.first放在查询的末尾:

@recipe = Recipe.where(:user_recipe_id => params[:id]).first

或使用仅返回一条记录的ActiveRecord查找程序:

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