使用Carrierwave将多张照片上传到Cloudinary仅上传一张照片

时间:2018-11-26 21:05:10

标签: ruby-on-rails activerecord carrierwave cloudinary acts-as-taggable

我一直在寻找答案很久了,但是没有任何帮助。我一直在关注Github页面上关于Carrierwave(https://github.com/carrierwaveuploader/carrierwave/blob/master/README.md#multiple-file-uploads)的教程。就像说明(用餐厅代替用户,用头像代替照片)一样,我有以下内容(我正在使用Rails 5.2.1):

rails g migration add_photos_to_restaurant photos:json

# app/models/restaurant.rb
class Restaurant < ApplicationRecord
  belongs_to :user
  mount_uploaders :photos, PhotoUploader
end


# app/views/restaurants/_form.html.erb
<div class="container" style="margin-bottom: 200px;">
  <div class="row">
    <div class="col-xs-6 col-sm-offset-3">
      <div class="form-inputs">
        <%= simple_form_for(@restaurant) do |f| %>
          <% if @restaurant.errors.any? %>
            <ul>
              <% @restaurant.errors.full_messages.each do |message| %>
              <li>
                <%= message %>
              </li>
              <% end %>
            </ul>
          <% end %>
          #[...]
          <%= f.file_field :photos, multiple: true %>
      </div>
      <div class="form-actions">
          <%= f.submit class: "btn btn-success" %>
          <%= link_to 'Back', restaurants_path, class: "btn btn-primary" %>
      </div>
    </div>
        <% end %>
  </div>
</div>


# app/controllers/restaurants_controller.rb
class RestaurantsController < ApplicationController
  skip_before_action :authenticate_user!, only: [ :index, :show ]
  before_action :set_restaurant, only: [ :show, :edit, :update, :destroy ]

  def index
    @restaurants = Restaurant.all
  end

  def show
  end

  def new
    @restaurant = Restaurant.new
  end

  def create
    @restaurant = Restaurant.new(restaurant_params)
    @restaurant.user = current_user
    if @restaurant.save
      redirect_to restaurant_path(@restaurant)
    else
      render :new
    end
  end

  def edit
  end

  def update
    if @restaurant.update(restaurant_params)
      redirect_to restaurant_path(@restaurant)
    else
      render :edit
    end
  end

  def destroy
    @restaurant.destroy
    redirect_to restaurants_path
  end

  private

  def set_restaurant
    @restaurant = Restaurant.find(params[:id])
  end

  def restaurant_params
    params.require(:restaurant).permit(
      #[...],
      {photos: []}
      )
  end
end

执行此操作后得到的是,只有第一张照片保存在restaurant.photo中,但是在Cloudinary上,我收到了所有照片。

另一件事是,我不能与此一起使用可标记标签的gem,因为如果这样做,我会收到此错误:

PG::UndefinedFunction: ERROR:  could not identify an equality operator for type json
LINE 1: ..., restaurants.created_at, restaurants.updated_at, restaurant...

这与在餐厅表中将照片作为json列有关。也没有找到解决方法。我希望我可以继续使用Acts作为可标记标签,因为它对于我正在构建的类型网站非常有用。因此,现在我不得不评论与该宝石有关的所有事情。

有人可以帮我摆脱困境吗?非常感谢。

0 个答案:

没有答案