我正在通过Youtube tutorial在我的网站上安装Paperclip gem。到了最后一步,但它返回了以下错误,不知道我哪里出错..
错误 -
NoMethodError in Houses#index
undefined method `image' for nil:NilClass
<%= image_tag @house.image.url(:medium) %>
包含代码以在index.html.erb中显示图像,所以我放入了:
<%= image_tag @house.image.url(:medium) %>
正如教程指示但它不喜欢那个&amp;我上传图片并刷新索引页面以查看图片时返回错误。
有人知道我哪里出错吗?
所有相关代码如下:
index.html.erb -
<h2><%= link_to "Add a House", new_house_path %></h2>
<% @houses.each do |house| %>
<div class="house">
<%= image_tag @house.image.url(:medium) %>
<h2><%= house.title %></h2>
<h2>£<%= house.price %></h2>
<p><%= house.description %></p>
</div>
<% end %>
house.rb -
class House < ActiveRecord::Base
validates :title, presence: true
validates :price, presence: true
validates :description, presence: true
validates :image, presence: true
has_attached_file :image, styles: { large: "600x600", medium: "300x300", thumb: "150x150#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end
new.html.erb
<%= simple_form_for @house, html: { multipart: true } do |form| %>
<%= form.input :title, label: "House title" %>
<%= form.input :price, label: "House price" %>
<%= form.input :description, label: "Describe your house" %>
<%= form.input :image, as: :file, label: "Image of house" %>
<%= form.button :submit %>
<% end %>
houses.controller.erb -
class HousesController < ApplicationController
def index
@houses = House.page(params[:page]).per(20).order(created_at: :desc)
end
def new
@house = House.new
end
def create
@house = House.new(params.require(:house).permit(:title, :price, :description, :image))
if @house.save
redirect_to root_path
else
render "new"
end
end
end