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

时间:2015-02-22 22:42:07

标签: ruby-on-rails paperclip undefined-symbol

我正在尝试使用回形针,但它无法识别附件的符号 - :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) %>

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

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

1 个答案:

答案 0 :(得分:0)

我的猜测是你以某种方式调用你的recipes/_recipe.html.erb部分:

render @recipes

将每个Recipe存储在您的部分中可用的本地变量recipe中的内容。

在你偏爱中,你正在调用你的Recipe,因为它是一个类实例变量。只需将部分中的@recipe来电更改为recipe,您就可以了。