2016-09-04 5 views
0

У меня есть вид товара, который содержит название и содержание. Я хочу добавить загрузчик файлов в форму, и я хочу, чтобы этот загрузчик файлов мог загружать изображение или несколько изображений без необходимости отправки формы статьи.Rails 5: Загрузить изображение в формате товара

Я имею в виду, когда я создаю новую статью и, прежде чем я нажмите представить форму articel, я хотел бы добавить картинку, и я могу загрузить фотографии с помощью файла пользователя, и когда я выбрал картинку, чтобы быть загружены, изображения будут отправлены непосредственно в облачное хранилище, а затем миниатюра появится под кнопкой . Просмотрите кнопку. затем, когда I нажмите на миниатюре, URL-адрес изображения появится в текстовой области.

Как сделать загрузчик файлов таким? Я просматривал, но не нашел способ, я просто нашел, как отображать миниатюру перед загрузкой на хранение.

Я использую Carrierwave для загрузки изображений и облачных вычислений для облачного хранения.

и у меня есть две таблицы и контроллер

Статьи таблицы

def change 
    create_table :articles do |t| 
    t.string :title 
    t.text :content 
    t.string :cover 
end 

Article_images стол

def change 
    create_table :article_images do |t| 
    t.string :image 
    t.integer :article_id 

    t.timestamps 
end 

Статья модель

class Article < ApplicationRecord 
    mount_uploader :cover, ImageUploader 
    has_many :article_images, dependent: :destroy 
    accepts_nested_attributes_for :article_images, :reject_if => :all_blank, :allow_destroy => true 
    validates :title, :cover, :content, presence: true 
    validates :title, uniqueness: true 
end 

Article_image модель

class ArticleImage < ApplicationRecord 
    mount_uploader :image, ImageUploader 
    belongs_to :article 
end 

Статьи Контроллер

class ArticlesController < ApplicationController 
    before_action :authenticate_admin!, only: [:edit, :update, :destroy] 
    before_action :set_article, only: [:show, :edit, :update, :destroy] 

    def index 
    @articles = Article.all 
    end 

    def show 
    end 

    def new 
    @article = Article.new 
    end 

    def edit 
    end 

    def delete_image 
    images = ArticleImage.find(params[:id]) 
    article_id = images.article.id 
    images.destroy 

    respond_to do |format| 
     format.html { redirect_to article_show_url(article_id), notice: 'Image was successfully deleted.' } 
     format.json { head :no_content } 
    end 
    end 

    def create 
    @article = Article.new(article_params) 

    respond_to do |format| 
     if @article.save 
     format.html { redirect_to @article, notice: 'Article was successfully created.' } 
     format.json { render :show, status: :created, location: @article } 
     else 
     format.html { render :new } 
     format.json { render json: @article.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def update 
    respond_to do |format| 
     if @article.update(article_params) 
     format.html { redirect_to @article, notice: 'Article was successfully updated.' } 
     format.json { render :show, status: :ok, location: @article } 
     else 
     format.html { render :edit } 
     format.json { render json: @article.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

    def destroy 
    @article.destroy 
    respond_to do |format| 
     format.html { redirect_to articles_url, notice: 'Article was successfully destroyed.' } 
     format.json { head :no_content } 
    end 
    end 

    private 
    def set_article 
     @article = Article.find(params[:id]) 
    end 
    def article_params 
     params.require(:article).permit(:title, :content, :cover, :cover_cache, article_images_attributes: [:id, :image, :image_cache, :_destroy]) 
    end 
end 

EDIT:

вот мой _form

<div class="form-grup"> 
     <p> 
     <%= f.label :title %>:<br/> 
     <%= f.text_field :title %> 
     </p> 
    </div> 

    <div class="form-grup"> 
     <p> 
     <%= f.label :cover %>:<br/> 
     <%= f.file_field :cover %> 
     <%= f.hidden_field :cover_cache, :value => f.object.cover_cache %> 
     </p> 
    </div> 


    <div class="form-grup"> 
     <p> 
     <%= f.label :content %>:<br/> 
     <%= f.cktext_area :content, :ckeditor => {:customConfig => asset_path('ckeditor/config.js')} %> 
     </p> 
    </div> 

    <div class="form-grup"> 
     <p> 
     <%= f.label :image, "Upload images:" %> 
     <%= f.fields_for :article_images do |image| %> 
      <%= render 'article_image_fields', f: image %><br/> 
     <% end %> 
     <%= link_to_add_association 'add image', f, :article_images %> 
     </p> 
    </div> 

    <div class="form-grup actions"> 
     <%= f.submit %> 
    </div> 

здесь _article_image_fields

<% if f.object.image.present? %> 
    <div class="field"> 
     <%= image_tag(f.object.image_url, size: "100x100") %> 
    </div> <br/> 
    <div class="field"> 
     <%= f.file_field :image, type: :file %> 
     <%= f.hidden_field :image_cache, :value => f.object.image_cache %> 
    </div> 
    <div class="field"> 
     <%= link_to_remove_association "remove image", f %> 
    </div> 
<% else %> 

    <div class="field"> 
     <%= f.file_field :image, type: :file %> 
     <%= f.hidden_field :image_cache, :value => f.object.image_cache %> 
    </div> 
    <div class="field"> 
     <%= link_to_remove_association "remove image", f %> 
    </div> 
<% end %> 

в моей форме, когда я создаю новую статью, в файле загрузить , когда я нажимаю просмотра и я выбрал картинку, изображение не напрямую загружены на cloudinary, но он принял выжидательную представленный на форма статей. когда я представить статью, фотографии будут загружены

что я хочу, когда я выбираю картинку, изображение мгновенно закачанный в cloudinary без, чтобы нажать на представить кнопку в моей форме статьи, так что я может получить URL-адрес изображения в текстовой области.

ответ

0

Посмотрите на Rails 4 multiple image or file upload using carrierwave.

В частности, обратите внимание, что действие new посылает как Article.new, так и ArticleImage.new и использование field_for.

Ваша структура хорошая, но, не глядя на вашу форму и не уточняя, как далеко вы прошли, трудно понять, какой результат вы хотите точно.

+0

hi @fbelanger, я только что редактировал мой вопрос: D – June

Смежные вопросы