使用回形针为现有公司上传图片

时间:2016-11-25 20:24:03

标签: ruby-on-rails paperclip

我有一个使用paperclip的图片模型

class Picture < ActiveRecord::Base
  belongs_to :company

  has_attached_file :image, styles: { medium: "300x300>", 
                                      thumb: "100x100>" }, 
                                      default_url: "/images/:style/missing.png"
  validates_attachment :image, content_type: { content_type:
                                                          ["image/jpg", 
                                                           "image/jpeg", 
                                                           "image/png"] }
end

和公司模式

class Company < ActiveRecord::Base
  has_attached_file :logo_image, styles: { medium: "300x300>", thumb: "100x100>" }
  has_and_belongs_to_many :primary_categories
  has_and_belongs_to_many :secondary_categories
  has_many :pictures, dependent: :destroy
  accepts_nested_attributes_for :pictures, allow_destroy: true

end

我使用回形针为公司加载徽标图像,但图片模型也会使用回形针为公司存储多张照片。当我最初使用从cocoon gem获得的嵌套属性创建新公司时,我能够将多个图像附加到公司。我试图将这些问题分开。当我创建公司时,我不会添加照片。我将在访问公司展示页面时添加照片,然后点击链接将我带到公司/:id / pictures path。这里将存储我公司的照片和上传新照片的表格。

即使我收到照片正在上传的通知,我的初步尝试也不允许我上传照片。

在公司/:id / pictures我有表格

<div class="container">
  <%= form_for([:admin, @company], class: "form", html: { multipart: true }) do |f| %>
    <% if @company.errors.any? %>
      <div id="error_explanation">
        <h2><%= pluralize(@company.errors.count, "error") %> prohibited this company from being saved:</h2>
        <ul>
        <% @company.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
        </ul>
      </div>
    <% end %>
    <div class="form-group">
      <h1>Add picture</h1>
      <%= f.fields_for :pictures do |image| %><br>
       <%= render 'picture_fields', f: image %>
      <% end %>
    </div>

    <div class="actions">
      <%= f.submit "Save", class: "btn btn-primary" %>
    </div>
  <% end %>

</div>

在我的照片控制器中

class Admin::PicturesController < ApplicationController
  before_action :set_company

  def create
    @picture = Picture.new(picture_params)
    if @picture.save
      redirect_to admin_company_pictures_path(@picture), notice: 'Picture uploaded successfully.'
    else
      render :index
    end
  end

  def index
    @pictures = @company.pictures
    @picture = Picture.new
  end

  def destroy
    @picture = @company.pictures.find(params[:id])
    @picture.destroy
    redirect_to admin_company_pictures_url(@company)
  end

  private

    def picture_params
      params.require(:picture).permit(:image)
    end

    def set_company
      @company = Company.find(params[:company_id])
    end
end

文件上传按钮甚至不显示,我只看到提交按钮。我觉得我过于复杂,但如果有人不得不面对类似的问题,我会感激任何提示。

0 个答案:

没有答案