【发布时间】:2015-09-19 18:06:39
【问题描述】:
我正在使用 Paperclip,我唯一的问题是在我的图像标签中,我有一个未定义的方法“图像”。
<%= image_tag @posts.image.url(:medium) %>
是我的错误发生的地方。当我加载一个新的迁移时,我不小心做了“rails g paperclip user image”而不是“rails g paperclip posts image”,所以我进入我的代码并将“user”更改为“posts”。我问了类似的问题,有人提到它与我的 schema.rb 文件有关(?)。
为了安全起见,这是我的后期控制器:
class PostsController < ApplicationController
def index
@posts = Post.all.order('created_at DESC')
end
def new
@post = Post.new
if @post.save
redirect_to @post
else
render 'new'
end
end
def create
@post = Post.new(post_params)
@post.save
redirect_to @post
end
def show
@post = Post.find(params[:id])
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update(params[:post].permit(:title, :body))
redirect_to @post
else
render 'edit'
end
end
def destroy
@post = Post.find(params[:id])
@post.destroy
redirect_to root_path
end
private
def post_params
params.require(:post).permit(:title, :body, :image)
end
end
但这是我的迁移文件:
class AddAttachmentImageToUsers < ActiveRecord::Migration
def self.up
change_table :posts do |t|
t.attachment :image
end
end
def self.down
remove_attachment :posts, :image
end
end
还有我的 user.rb 文件:
has_attached_file :image, :styles => { large: '600x600>', medium: '300x300>', thumb: '150x150#' }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
【问题讨论】:
-
我猜应该是
@post.image。 -
这就是问题所在
-
@posts我认为是post对象的集合。您需要为每个post获取image。所以你需要遍历@posts,并且对于每个post,你可以使用这个<%= image_tag post.image.url(:medium) %>,我猜这会起作用。 -
所以你建议摆脱
@?我认为这行不通 -
不,我不是说要摆脱
@,我建议请遍历@posts的列表并尝试为每个帖子获取image
标签: ruby-on-rails ruby-on-rails-3 imagemagick paperclip erb