【问题标题】:Why is adding multiple images to a gallery object not working at all为什么将多个图像添加到画廊对象根本不起作用
【发布时间】:2014-09-19 12:07:34
【问题描述】:

我正在创建一个图库,您可以在其中通过表单上传多张图片。

该表单嵌套在另一个表单中,当提交该表单时,它应该创建包含附件图像的图库。当我检查输出时,我得到了这意味着它根本没有向画廊对象提交正确的图像:

Parameters: {
    "utf8"=>"✓", 
    "authenticity_token"=>"BJhkDx7rCRMIlXQ6T9FskXZe7+fdYxj0qm+VnCaC51w=", 
    "book"=>{ 
        "jacket_cover" =>#<ActionDispatch::Http::UploadedFile:0x000001025d3128 
        @tempfile=#<File:/var/folders/mf/srx7jt8s2rdg0mn5hr98cvz80000gn/T/RackMultipart20140918-47766-1g9kyas>, @original_filename="559a7a477253d58f891f8e852162dfac.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"book[jacket_cover]\"; filename=\"559a7a477253d58f891f8e852162dfac.jpg\"\r\nContent-Type: image/jpeg\r\n">,
        "title"=>"zd szw wrwr", 
        "synopsis"=>"<p>cfdcrgcgrere</p>\r\n", 
        "body"=>"<p>rccgregrrgerereg</p>\r\n", 
        "age"=>"19", 
        "publisher"=>"Dove books", 
        "author_attributes"=>{
            "name"=>"zsdxfrrwg", 
            "biography"=>"<p>exffwfwefewewf</p>\r\n"}, 
        "gallery_attributes"=>{
            "images_attributes"=>{
            "0"=>{
                "file"=>[#<ActionDispatch::Http::UploadedFile:0x000001025d20e8 @tempfile=#<File:/var/folders/mf/srx7jt8s2rdg0mn5hr98cvz80000gn/T/RackMultipart20140918-47766-tk1rdb>, @original_filename="23ebb202a3655c6d0947251cce8625b6.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"book[gallery_attributes][images_attributes][0][file][]\"; filename=\"23ebb202a3655c6d0947251cce8625b6.jpg\"\r\nContent-Type: image/jpeg\r\n">, #<ActionDispatch::Http::UploadedFile:0x000001025d1ff8 @tempfile=#<File:/var/folders/mf/srx7jt8s2rdg0mn5hr98cvz80000gn/T/RackMultipart20140918-47766-j3ji7c>, @original_filename="559a7a477253d58f891f8e852162dfac.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"book[gallery_attributes][images_attributes][0][file][]\"; filename=\"559a7a477253d58f891f8e852162dfac.jpg\"\r\nContent-Type: image/jpeg\r\n">]
            }
            }
        }
    }, "commit"=>"Create Book"

}

books_controller 处理包含图片的画廊的提交:

class BooksController < ApplicationController
  before_action :set_book, only: [:show, :edit, :update, :destroy]
  before_filter :authenticate_user!, only: [:new, :edit, :update, :destroy]

  # GET /books
  # GET /books.json
  def index
    @books = Book.order('created_at DESC').all
  end

  # GET /books/1
  # GET /books/1.json
  def show
    # @book = Book.find(params[:id])
    @book = Book.friendly.find(params[:id])
    @gallery = @book.gallery
  end

  # GET /books/new
  def new
    @book = Book.new
    @book.build_author
    @gallery = @book.build_gallery 
    @gallery.images.build
  end

  # GET /books/1/edit
  def edit
  end

  # POST /books
  # POST /books.json
  def create
    #raise params.inspect
    @book = Book.new(book_params)

    #binding.pry

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

  # PATCH/PUT /books/1
  # PATCH/PUT /books/1.json
  def update
    respond_to do |format|
      if @book.update(book_params)
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @book.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /books/1
  # DELETE /books/1.json
  def destroy
    @book.destroy
    respond_to do |format|
      format.html { redirect_to books_url }
      format.json { head :no_content }
    end
  end

  # Get authors
  # def reviews
  # @book = Book.friendly.find(params[:id])
  # @reviews = @movie.reviews

  #   respond_to do |format|
  #     format.html { render 'reviews/index' } # index.html.erb
  #     format.json { render json: @movies }
  #   end
  # end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      # @book = Book.find(params[:id])
      @book = Book.friendly.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:title, :synopsis, :body, :age, :publisher, :jacket_cover, author_attributes: [:name,:biography], gallery_attributes: [:name, :book_id ] )    
    end
end

book.rb

class Book < ActiveRecord::Base

    has_attached_file :jacket_cover, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
    validates_attachment_content_type :jacket_cover, :content_type => /\Aimage\/.*\Z/

    validates :jacket_cover, :title, :slug, :synopsis, :body, :age, :publisher, presence: true
    validates_uniqueness_of :title

    extend FriendlyId
    friendly_id :title, use: [:slugged, :finders]

    belongs_to :author
    has_one :gallery
    has_many :stories

    accepts_nested_attributes_for :author
    accepts_nested_attributes_for :gallery

    scope :available, ->{ where(available: true) }
    scope :unavailable, ->{ where(available: [nil, false]) }

end

图像.rb

class Image < ActiveRecord::Base

    belongs_to :gallery

    has_attached_file :file, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
    validates_attachment_content_type :file, :content_type => /\Aimage\/.*\Z/

end

画廊.rb

class Gallery < ActiveRecord::Base

    belongs_to :books
    has_many :images
    accepts_nested_attributes_for :books
    accepts_nested_attributes_for :images, :allow_destroy => true

end

galleries_controller.rb

class GalleriesController < ApplicationController
  before_action :set_gallery, only: [:show, :edit, :update, :destroy]

  def index
    @galleries = Gallery.all
  end

  def show
    @gallery = Gallery.find(params[:id])
    @images = @gallery.images
  end

  def new
    @gallery = Gallery.new
    #@gallery.images.build
    # @images = @gallery.build_images 
    # @gallery.images.build
  end

  def edit
    @gallery.images.build
  end

  def create
    @gallery = Gallery.new(gallery_params)
    @image = Image.create()
    #@gallery.images.build 

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

  def update
    respond_to do |format|
      if @gallery.update(gallery_params)
        format.html { redirect_to @gallery, notice: 'Gallery was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @gallery.errors, status: :unprocessable_entity }
      end
    end
  end

  def destroy
    @gallery.destroy
    respond_to do |format|
      format.html { redirect_to galleries_url }
      format.json { head :no_content }
    end
  end

  private

    def set_gallery
      @gallery = Gallery.find(params[:id])
    end

    def gallery_params
      params.require(:gallery).permit(:name, :book_id, :image)
      #params.require(:gallery).permit(:name, :book_id, :images[], images_attributes: [:id, :file []])
      #params.require(:gallery).permit(:name, :book_id, :images[images_attributes: [:file]])
      # params.require(:gallery).permit(:name, :book_id, images_attributes: [:id, :image[:file]])
    end
end

在此处添加了提交图片库的表单:

<%= simple_form_for(@book, :html => { :multipart => true } ) do |f| %>
  <%= f.error_notification %>

  <div class="inputs">
    <div id="image" class="field">
      <h3>Add the book image here</h3>
      <div class="single-file">
        <div class="file_upload">
           <%= f.file_field :jacket_cover %>
        </div>
      </div>
    </div>

    <div id="title" class="field">
      <h3>Add the title</h3>
      <%= f.input :title %>
    </div>
    <div id="synopsis" class="field">
      <h3>Add the book synopsis</h3>
      <%= f.input :synopsis, :as => :ckeditor, :label => false, :input_html => {  :ckeditor => { :toolbar => 'Full', :height => 400 } } %>
    </div>
    <div id="body" class="field">
      <h3>Add the book body summary here</h3>
      <%= f.input :body, :as => :ckeditor, :label => false, :input_html => {  :ckeditor => { :toolbar => 'Full', :height => 400 } } %>
    </div>
    <div id="age" class="field">
      <h3>Add the book age group</h3>
      <%= f.input :age, collection: [['3-7', '3-7'],['7-11', '7-11'],['11-14', '11-14']], prompt: "Select age range" %>
    </div>
    <div id="publisher" class="field">
      <h3>Who published the book</h3>
      <%= f.input :publisher %>
    </div>

    <div id="school" class="field">
      <h3>Schools reading this book (add the name and full address of the school)</h3>
      <%= f.simple_fields_for :schools, :wrapper => 'inline' do |builder| %>
        <%= render 'school_fields', :f => builder %>
        <%= link_to_add_association 'add school', f, :schools, :render_options => {:wrapper => 'inline' }, :class => 'fa fa-plus' %>
      <% end %>
    </div>

  </div>
  <%#= f.select( :author_id, Author.all.map {|u| [u.name,u.id]}, {:include_blank => false, prompt: "No Author"} ) %>
  <div id="author-inputs">
    <h3>Add author</h3>
    <%#= link_to 'New Author', new_author_path, :remote => true, :id => "new_author_link" %>
    <%= f.simple_fields_for :author, :wrapper => 'inline' do |builder| %>
      <%= render 'author_fields', :f => builder %>
    <% end %>
  </div>

    <%= f.simple_fields_for :gallery do |builder| %>
      <%= render 'galleries/form', :f => builder %>
    <% end %>


  <div class="actions">
    <%= f.button :submit %>
  </div>
<% end %>

当我在数据库控制台中签入时,我在搜索 Gallery.all 时看不到画廊内的任何图像

我创建了一个包含所有必要信息的 gist 文件。

任何人都可以为我解释一下吗?

【问题讨论】:

  • 您是否在 Book 模型中添加了accepts_nested_attributes_for :images?
  • 您的 permit_params 中也没有 images_attributes,型号是什么。你有has_many :galleries,which has_many :images?,所以它有书has_many ?
  • 我可以看看你的画廊模型和控制器吗?
  • navinspm Ivan Shamatov 我已经编辑了文档
  • 我认为我的书和画廊模型对吗?

标签: ruby-on-rails ruby ruby-on-rails-4 paperclip image-gallery


【解决方案1】:

主要问题在于您的父窗体和模型关系。

在您的图书模型中,您应该使用belongs_to :gallery 而不是has_one :gallery。还要检查您的数据库。 books 表应该有gallery_id。作为数据库概念,belongs_to 应该有父表 ID。所以模型应该是:

class Book < ActiveRecord::Base

    has_attached_file :jacket_cover, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
    validates_attachment_content_type :jacket_cover, :content_type => /\Aimage\/.*\Z/

    validates :jacket_cover, :title, :slug, :synopsis, :body, :age, :publisher, presence: true
    validates_uniqueness_of :title

    extend FriendlyId
    friendly_id :title, use: [:slugged, :finders]

    belongs_to :author
    belongs_to :gallery
    has_many :stories

    accepts_nested_attributes_for :author
    accepts_nested_attributes_for :gallery

    scope :available, ->{ where(available: true) }
    scope :unavailable, ->{ where(available: [nil, false]) }

end

你的画廊模型应该是这样的:

class Gallery < ActiveRecord::Base

    has_many :books
    has_many :images
    accepts_nested_attributes_for :books
    accepts_nested_attributes_for :images, :allow_destroy => true

end

表单中的父模型应该是gallery 模型而不是book。并在您的图库控制器中进行必要的更改。

【讨论】:

  • 我看不出这有什么帮助??
  • 嘿 Nitin 那么&lt;%= simple_form_for(@book, :html =&gt; { :multipart =&gt; true }) do |f| %&gt; 应该是&lt;%= simple_form_for(@gallery, :html =&gt; { :multipart =&gt; true }) do |f| %&gt; 吗?当您说在画廊控制器中进行必要的更改时,您的意思是采用书籍控制器中添加的内容并使其适用于画廊吗?
  • 是的,您应该将画廊作为父模型。所以保存画廊而不是书,并将所有逻辑放在画廊控制器中。您还必须更改控制器中的许可参数
  • 真的吗?但重点是这个人添加了一本书而不是画廊,画廊是书的附属品,书是整个事情中最重要的部分。如果是画廊,那么这个逻辑肯定是错误的吗?该过程是:您登录,去添加书籍,您添加书籍详细信息在附加到书籍的书籍库中添加一些图像,然后保存表单,基本上应该有一本带有图库的书籍。
  • 我是完全没有明白这一点还是完全错了?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-06-28
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多