Ruby on rails 为什么向gallery对象添加多个图像根本不起作用

Ruby on rails 为什么向gallery对象添加多个图像根本不起作用,ruby-on-rails,ruby,ruby-on-rails-4,paperclip,image-gallery,Ruby On Rails,Ruby,Ruby On Rails 4,Paperclip,Image Gallery,我正在创建一个图库,您可以通过表单上传多个图像 该表单嵌套在另一个表单中,提交该表单时,它应创建包含附加图像的库。当我检查输出时,我得到这一信息,这意味着它根本没有向gallery对象提交正确的图像: Parameters: { "utf8"=>"✓", "authenticity_token"=>"BJhkDx7rCRMIlXQ6T9FskXZe7+fdYxj0qm+VnCaC51w=", "book"=>{ "jacket_co

我正在创建一个图库,您可以通过表单上传多个图像

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

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_控制器处理画廊的提交,其中包含图像:

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
image.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
超级控制器.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 %>
当我在db控制台中进行检查时,我在搜索gallery.all时在gallery中看不到任何图像

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


有人能帮我解释一下吗?

主要问题是您的父窗体和模型关系

在您的图书模型中,您应该拥有属于:图库,而不是拥有一个:图库。还要检查你的数据库。books表应具有gallery_id。作为数据库概念所属,books表应具有父表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 controller中进行必要的更改。

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

在您的图书模型中,您应该拥有属于:图库,而不是拥有一个:图库。还要检查你的数据库。books表应具有gallery_id。作为数据库概念所属,books表应具有父表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


表单中的父模型应为图库模型,而不是书本。并在图库控制器中进行必要的更改。

是否在书本模型中为:图像添加了accepts\u nested\u attributes\u?许可参数中也没有图像属性,模型是什么。你有很多画廊吗?其中有很多图片?,所以它有书有很多?我能看看你的图库模型和控制器吗?navinspm Ivan Shamatov我编辑了文档我的书和图库模型是对的,我想?你在你的书模型中为:图像添加了接受嵌套属性吗?你的许可参数中也没有图像属性,模型是什么。你有很多:图库,其中有很多:图像吗?所以它有书有很多?我能看看你的图库模型和控制器吗?纳文斯普姆·伊万·沙马托夫我编辑了文件我的书和图库模型是对的,我想?我看不出这有什么帮助??嘿,尼廷,所以{:多部分=>真的}多部分}应该是{:多部分=>真的}多部分}?当您说在gallery controller中进行必要的更改时,您的意思是接受books controller中添加的内容并使其适用于gallery吗?是的,您应该将gallery作为父模型。所以保存gallery而不是book,并将所有逻辑放在gallery控制器中。您还必须更改控制器中的许可参数真的吗?但关键是,这个人是在添加一本书,而不是一个画廊,画廊是这本书的一个附属机构。这本书是整件事中最重要的部分。如果是画廊,那么这个逻辑肯定是错误的吗?这个过程是:你登录,转到添加书,你添加书的详细信息,在书的附加图库中添加一些图像,然后保存表单,基本上应该有一本书里面有图库。我当时完全不明白,还是完全错了?我看不出这有什么帮助??嘿,Nitin,所以{:multipart=>true}do | f |%>应该是{:multipart=>true}do | f |%>?当您说在gallery controller中进行必要的更改时,您的意思是接受books controller中添加的内容并使其适用于gallery吗?是的,您应该将gallery作为父模型。所以保存gallery而不是book,并将所有逻辑放在gallery控制器中。您还必须更改控制器中的许可参数真的吗?但关键是,这个人是在添加一本书,而不是一个画廊,画廊是这本书的一个附属机构。这本书是整件事中最重要的部分。如果是画廊,那么这个逻辑肯定是错误的吗?这个过程是:你登录,转到添加书,你添加书的详细信息,在书的附加图库中添加一些图像,然后保存表单,基本上应该有一本书里面有图库。我完全不明白,还是完全错了?