我正在创建一个应用程序,需要能够允许用户将多个图像上传到帖子。我正在使用Paperclip上传图片,目前只上传一张图片。我正在努力了解如何在现有结构上实现它以允许多个图像。
我想的过程是这样的,我对编程很新,所以让我知道我是不是错了。我会采取大胆的步骤,我对其他人更不确定:
以下是我最为困惑的部分
post_controller和picture_controller有什么用?这是我目前的post_controller:
class PostsController < ApplicationController
before_action :find_posts, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
before_action :authenticate_user!, except: [:index, :show, :home]
def home
end
def index
if params[:category].blank?
@posts = Post.all.order("created_at DESC")
else
@category_id = Category.find_by(name: params[:category]).id
@posts = Post.where(category_id: @category_id).order("created_at DESC")
end
end
def show
@inquiries = Inquiry.where(post_id: @post).order("created_at DESC")
@random_post = Post.where.not(id: @post).order("RANDOM()").first
end
def new
@post = current_user.posts.build
end
def create
@post = current_user.posts.build(post_params)
if @post.save
redirect_to @post
else
render 'new'
end
end
def edit
end
def update
if @post.update(post_params)
redirect_to @post
else
render 'edit'
end
end
def destroy
@post.destroy
redirect_to root_path
end
def upvote
@post.upvote_by current_user
redirect_to @post
end
def downvote
@post.downvote_by current_user
redirect_to @post
end
private
def find_posts
@post = Post.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :price, :description, :location, :category_name, :contact_number, :image)
end
end
如何更改帖子/表单以接受图片中的多张图片?目前:
.edit-container
= simple_form_for @post, html: { multipart: true } do |f|
.edit-form
= f.input :title
= f.input :location, disabled: true
= f.input :price
= f.input :description
= f.input :contact_number, placeholder: "(999) 999-9999"
= f.label "Category"
= f.text_field :category_name, data: {autocomplete_source: Category.order(:name).map(&:name)}, placeholder: "Choose a category"
= f.file_field :image, multiple: true, name: "post[image]"
= f.button :submit
%script
$('#post_location').val("#{request.location.city}, #{request.location.state}")
最后,我知道我需要做一些像
这样的事情- @picture.each do |image|
但是当我尝试它时它没有用。这就是我现在所拥有的:
.clearfix
.post_image_description
= image_tag @post.image.url if @post.image?
.description= simple_format(@post.description)
.description
Contact:
= @post.contact_number
这是索引
#posts
.row
- @posts.each do |post|
.col-xs-12.col-sm-6.col-md-4.col-lg-3
.post
.post_content
.title
%h2
= link_to truncate((post.title), length: 25), post
%p
$
= post.price
.post_image
= link_to image_tag(post.image.url), post
我希望这是一个真实而详细的答案的足够信息。我已经花了将近一个星期的时间试图解决这个问题,所以我真的希望有人可以帮我解决这个问题。
答案 0 :(得分:0)
您可能会发现carrierwave
gem更适合此项目,并且更易于设置。您不需要单独的图片模型。
按照此处的说明操作:
https://github.com/carrierwaveuploader/carrierwave
在你的情况下,你需要这样的东西:
class Post < ActiveRecord::Base
mount_uploaders :pictures, PictureUploader
end
答案 1 :(得分:0)
经过大约一个星期左右的努力才能让它发挥作用,我认为载波是一个更好的选择,并遵循这个answer来实现它到我当前的应用程序。它非常详细(尽管您需要将其调整为当前的应用程序)。
答案 2 :(得分:-1)
您可以从jquery file upload中受益。这是通过jquery处理多个文件上传的一种非常简单的方法。阅读文档,如果有任何不清楚的地方,请告诉我。