nil:Nilclass 的回形针未定义方法 'photo_of_recipe'

paperclip undefined method 'photo_of_recipe' for nil:Nilclass

我正在尝试使用回形针,但它无法识别附件符号 - :photo_of_recipe。相反,当我尝试加载带有附件的食谱时,它显示:

undefined method `photo_of_recipe' for nil:NilClass

我运行:

rails g paperclip recipes photo_of_recipe

这是食谱模型的附件代码:

has_attached_file :photo_of_recipe, :styles => { large: "600x600",   
medium: "300x300", thumb: "100x100#" } 
validates_attachment_content_type :photo_of_recipe, :content_type => 
/\Aimage\/.*\Z/

我猜错误是由于 :photo_of_recipe 在技术上不是 Recipe 对象的属性。以下是 Recipe 对象的参数:

2.0.0-p598 :002 > Recipe
=> Recipe(id: integer, title: string, body: text, published_at:   
datetime, created_at: datetime, updated_at: datetime, user_id: 
integer, photo_of_recipe_file_name: string, 
photo_of_recipe_content_type: string, photo_of_recipe_file_size: 
integer, photo_of_recipe_updated_at: datetime) 

这是当我尝试加载食谱时来自 rails 控制台的消息:

Started GET "/" for 127.0.0.1 at 2015-02-24 17:50:16 -0500
Processing by RecipesController#index as HTML
Recipe Load (0.2ms)  SELECT "recipes".* FROM "recipes"
User Load (0.1ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = 
? LIMIT 1  [["id", 1]]
Rendered recipes/_recipe.html.erb (2.4ms)
Rendered recipes/index.html.erb within layouts/application (3.9ms)
Completed 500 Internal Server Error in 6ms

 ActionView::Template::Error (undefined method `photo_of_recipe' for  
 nil:NilClass):
 8:       </span>
 9:       <% end %>
10:   </h3>
11:   <% if @recipe.photo_of_recipe %>
12:     <%= image_tag @recipe.photo_of_recipe.url %>
13:     <%= image_tag @recipe.photo_of_recipe.url(:medium) %>
14:     <%= image_tag @recipe.photo_of_recipe.url(:thumb) %>

哦,:photo_of_recipe 在我的 recipe_params 配方控制器中是允许的,所以这不是问题。

这可能是因为我还没有创建 Photo_of_recipe 模型?我不想那样做,除非这是附件的常见做法。任何帮助将不胜感激。

我猜你是这样调用你的 recipes/_recipe.html.erb 部分的:

render @recipes

什么将每个 Recipe 存储在您的局部变量 recipe 中可用。

在你的部分中,你调用你的 Recipe 就像它是一个 class 实例变量。只需在您的部分中将对 @recipe 的任何调用更改为 recipe,您应该没问题。