繁体   English   中英

使用回形针和导轨显示嵌套图像

[英]Display a nested image with paperclip and rails

我有两个模型:Post和Picture

class Post < ActiveRecord::Base

has_many :picture, :dependent => :destroy


accepts_nested_attributes_for :picture, :allow_destroy => true, :reject_if => lambda { |t| t['pictures'].nil? }

end

class Picture < ActiveRecord::Base
belongs_to :posts 

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

图片具有回形针附件:图片

我创建了一个嵌套表单,但由于无法在显示页面中显示,因此无法知道我的图片是否正确保存。

这是我的表格:

 <%= form_for @post, html: { multipart: true} do |f| %>
  <% if @post.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>

      <ul>
      <% @post.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :description %><br>
    <%= f.text_area :description %>
  </div>
  <div class="field">
    <%= f.label :brand %><br>
    <%= f.text_field :brand %>
  </div>
  <div class="field">
    <%= f.label :model %><br>
    <%= f.text_field :model %>
  </div>


  <div class="field"><%= f.fields_for :picture do |p| %>

    <%= p.file_field :image %>


      <% end %>

  </div>

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

我的节目页面:

  <p id="notice"><%= notice %></p>


  <%= @post.picture.each do |pic|  %>

    <%= image_tag pic.image.url(:medium) %>
  <% end %>

<p>
  <strong>Title:</strong>
  <%= @post.title %>
</p>

<p>
  <strong>Description:</strong>
  <%= @post.description %>
</p>

<p>
  <strong>Brand:</strong>
  <%= @post.brand %>
</p>

<p>
  <strong>Model:</strong>
  <%= @post.model %>
</p>



<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

职位控制器:

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end

  # GET /posts/1
  # GET /posts/1.json
  def show
  end

  # GET /posts/new
  def new
    @post = Post.new
    @post.picture.build

  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  # POST /posts.json
  def create
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        if params[:image]

          params[:image].each { |image|
          @post.picture.create(image: image)
          }
        end

        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /posts/1
  # PATCH/PUT /posts/1.json
  def update
    respond_to do |format|
      if @post.update(post_params)
        format.html { redirect_to @post, notice: 'Post was successfully updated.' }
        format.json { render :show, status: :ok, location: @post }
      else
        format.html { render :edit }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /posts/1
  # DELETE /posts/1.json
  def destroy
    @post.destroy
    respond_to do |format|
      format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_post
      @post = Post.find(params[:id])
    end

     # Never trust parameters from the scary internet, only allow the white list through.
    def post_params
      params.require(:post).permit(:title, :description, :brand, :model,   picture_attributes: [ :id, :post_id, :image, :_destroy])
    end
end

当我加热创建帖子时,我没有错误地渲染帖子,但是没有显示图像,而是显示了:[[]”

终端输出

Processing by PostsController#show as HTML
  Parameters: {"id"=>"8"}
  Post Load (0.4ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1  [["id", 8]]
  Picture Load (0.3ms)  SELECT "pictures".* FROM "pictures" WHERE "pictures"."post_id" = ?  [["post_id", 8]]

我做错了什么吗?

您遇到的第一个问题是您错误地引用了关联:

#app/models/post.rb
class Post < ActiveRecord::Base
   has_many :pictures #-> plural
end

#app/models/picture.rb
class Picture < ActiveRecord::Base
   belongs_to :post #-> singular

   has_attached_file :image
   validates :image, content_type: { content_type: /\Aimage\/.*\Z/ }
end

您可以在此处查看有关关联名称的信息:

在此处输入图片说明

一个小技巧是在application.rb使用paperclip_defaults选项:

#config/application.rb
...
config.paperclip_defaults: {
    styles: { medium: "300x300>", thumb: "100x100>" },
    default_url: "/images/:style/missing.png"
}

这将允许您为应用程序中Paperclip的所有实现设置“默认值”,可以在每种模型中根据需要覆盖这些默认值。 只是让它看起来不那么混乱...


关于错误,您已准备就绪。 我认为问题是您的协会名称(见上文)。

这就是我要的:

#app/controllers/posts_controller.rb
class PostsController < ApplicationController
   def new
      @post = Post.new
      @post.pictures.build #-> plural
   end

   def create
      @post = Post.new post_params
      @post.save
   end

   private

   def post_params
      params.require(:post).permit(:title, :description, :brand, :model,   picture_attributes: [:image, :_destroy])
   end
end

然后,您可以使用以下形式:

#app/views/posts/new.html.erb
<%= form_for @post, multipart: true do |f| %>
   <%= f.fields_for :pictures do |p| %>
      <%= p.file_field :image %>
   <% end %>
   <%= f.submit %>
<% end %>

-

这应该正确地提交给您的数据库; 要显示图像,可以使用以下方法:

#app/views/posts/show.html.erb
<% @post.pictures.each do |picture| %>
   <%= image_tag picture.image.url %>
<% end %>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM