我正在尝试使用带有Ruby on Rails的Carrierwave gem在我的应用中显示图像。我正在使用Carrierwave支持的多图像上传选项。 Everythings工作正常,除非我去显示页面时出现此错误:帖子中的NoMethodError#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
答案 0 :(得分:1)
在post_params中,您已将图像参数定义为数组
params.require(:post).permit(:name, {image:[]})
您应该使用迭代从这个数组中检索图像:
<% @post.image.each do |image| %>
<%= image_tag image.url %>
<% end %>
将显示此帖子上发布的所有图片 或者如果您只想为帖子保存单个图像,请更改
params.require(:post).permit(:name, {image:[]})
到
params.require(:post).permit(:name, :image)
一切都会好起来的!
注意:强>
<%= image_tag @post.image[0].url %>
也适用于您编写的代码,因为它只会获取该图像数组中第一个图像的网址