0

我安装了 gem Paperclip,创建了两个模型

class Image < ActiveRecord::Base
  belongs_to :pizzerium
  attr_accessible :img, :pizzerium_id, :alt
    has_attached_file :img, :styles => { :medium => "300x300>", :thumb => "100x70>" }, :default_url => "/images/:style/missing.png"
  self.per_page = 6
end

还有比萨店

class Pizzerium < ActiveRecord::Base
  has_many :images
  accepts_nested_attributes_for :images, allow_destroy: true
  attr_accessible :description, :name, :url, :city, :meta_tag, :text_shedule, :time_begin, :time_end, :week_begin, :week_end
end

如果我在控制器中编写此代码:

@pizzerium = Pizzerium.where("city = ? AND url = ?", params[:city], params[:pizza]).first
@images = @pizzerium.images.all

并查看此代码:

<%= image_tag @images.first.img.url(:medium) %>

这是有效的,但如果我尝试

@pizzs = Pizzerium.where("city = ?", params[:city]).paginate(:page => params[:page])

或者

@pizzs = Pizzerium.includes(:images).where("city = ?", params[:city]).paginate(:page => params[:page])


<% @pizzs.each do |pizzerium| %>
<%= image_tag pizzerium.images.first.img.url %>
<% end %>

我看到错误:

常规中的 NoMethodError #index

显示 /home/wwju/rails/pizza/app/views/general/index.html.erb 其中第 14 行提出:

nil:NilClass 的未定义方法“img”

在 Rails 控制台中:

pizzs = Pizzerium.includes(:images).all
  Pizzerium Load (31.6ms)  SELECT "pizzeria".* FROM "pizzeria" 
  Image Load (10.3ms)  SELECT "images".* FROM "images" WHERE "images"."pizzerium_id" IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 14, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 32)
 => [#<Pizzerium id: 1, name: "Пицца-шляпа...
...

pizzs.first.images.first.img
 => /system/images/imgs/000/000/017/original/02.jpg?1369309592 

1.9.3p429 :027 > pizzs.each do |p|
1.9.3p429 :028 >     p.images.first.img
1.9.3p429 :029?>   end
NoMethodError: undefined method `img' for nil:NilClass
    from (irb):28:in `block in irb_binding'

(如果您发现任何错误,请告诉我,我正在努力提高我的英语水平。)

4

1 回答 1

0

我认为 pizzerium.images 是零。没有与比萨店对象关联的图像。

add check pizzerium.images? 
<%= image_tag pizzerium.images.first.img.url if pizzerium.images? %>
于 2013-05-27T11:37:53.860 回答