【发布时间】:2015-10-21 18:27:29
【问题描述】:
我正在尝试使用带有 Ruby on Rails 的 Carrierwave gem 在我的应用程序中显示图像。我正在使用 Carrierwave 支持的多图像上传选项。一切工作正常,除了当我转到显示页面时出现此错误:NoMethodError in Posts#show
这是代码
我的 show.html.erb 页面
<p id="notice"><%= notice %></p>
<%= image_tag @post.image.url %>
<p>
<strong>Name:</strong>
<%= @post.name %>
</p>
<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>
_form.html.erb
<%= form_for(@post , html: { multipart: true }) do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :image %><br>
<%= f.file_field :image , multiple: true %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
post_controller.rb
class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
# GET /posts
# GET /posts.json
def index
@posts = Post.all
end
# GET /posts/1
# GET /posts/1.json
def show
end
# GET /posts/new
def new
@post = Post.new
end
# GET /posts/1/edit
def edit
end
# POST /posts
# POST /posts.json
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /posts/1
# PATCH/PUT /posts/1.json
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
# DELETE /posts/1
# DELETE /posts/1.json
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_post
@post = Post.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def post_params
params.require(:post).permit(:name, {image:[]})
end
end
模型 post.rb
class Post < ActiveRecord::Base
mount_uploaders :image, ImageUploader
end
【问题讨论】:
-
似乎
@post.image返回一个数组。试试@post.image.first.id -
能否请您尝试 image_tag(@post.image_url) 并让我知道是否有效。谢谢
-
<%= image_tag @post.image %>并将params.require(:post).permit(:name, {image:[]})修复为params.require(:post).permit(:name, :image) -
我选择了第一个选项,但是当我显示图像时出现此错误pho.to/9nveX 在网站上搜索了此问题,但找不到图像未显示的原因goo.gl/8WSxxA
标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-3.2