多态回形针与 Rails 5 一起工作很奇怪

Polymorpic paperclip working strange with Rails 5

查看:

<div class="kitchen_settings">
<%= form_for @kitchen, :html => { :multipart => true, "data-ajax" => false} do |f| %>
     <%= f.text_field :title,placeholder: "#{current_user.fullname}'s Kitchen", autofocus: true %>
    <%= f.text_field :bio, placeholder: 'something about your kitchen' %>

    <%= f.fields_for :picture do |photo| %>
        <%= photo.file_field :avatar %>
    <% end %>
    <%= f.submit %>
<% end %>

kitchen_controller.rb

class KitchensController < ApplicationController
    before_action :authenticate_user!

    def new
        @kitchen = Kitchen.new
        @kitchen.build_picture
    end

    def create
        @kitchen = current_user.build_kitchen(kitchen_params)
    respond_to do |format|
        if @kitchen.save
          format.html { redirect_to dashboard_path, notice: 'Kitchen was successfully created.' }
          format.json { render :show, status: :created, location: dashboard_path }
        else
          format.html { render :new }
          format.json { render json: @kitchen.errors, status: :unprocessable_entity }
        end
      end
    end

    def show
        @kitchen = Kitchen.find (params[:id])
    end

    private
    def kitchen_params
        params.require(:kitchen).permit(:title,:bio, picture_attributes: [:avatar])
    end
end

kitchen.rb

class Kitchen < ApplicationRecord
  belongs_to :user

  has_one :picture, as: :imageable, dependent: :destroy
  accepts_nested_attributes_for :picture
end

picture.rb

class Picture < ApplicationRecord
    belongs_to :imageable, polymorphic: true

    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100"}, default_url: "/assets/:style/missing.png"
  validates_attachment :avatar, :presence => true,
    :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] },
    :size => { :in => 0..500.kilobytes }
end

And its giving me this error

我想要多态图片模型。我决定处理多态图片关联,但它总是回滚……卡住了。我附上了来自控制台的图像。谢谢!! Debugged it using binding.pry

您在 image.rb

中验证 imageable 时出现问题

当您将厨房与图像一起存储时。 Imageable 图片验证失败,因为尚未创建厨房。这就是它回滚的原因。

要确认,您可以暂时取消验证。

您需要使用 inverse_of 才能完成这项工作

image.rb

belongs_to :imageable, polymorphic: true , inverse_of: :image

kitchen.rb

has_one :picture, as: :imageable, dependent: :destroy,inverse_of: :imageable

我在两个协会中都添加了inverse_of。它告诉 rails 这些关联彼此相反,因此如果设置了其中任何一个,则不要进行查询以获取另一个。

这样,如果您设置任何关联,那么其他关联将自动设置,并且验证不会失败。

Here 是一个不错的博客 inverse_of 用途。

在 Rails 5 中,每当我们定义一个 belongs_to 关联时,在 change.To 更改此行为后,默认情况下需要关联记录存在 我设法做到了这样:

picture.rb

class Picture < ApplicationRecord
    belongs_to :imageable, polymorphic: true, optional: true

    has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100"}, default_url: "/assets/:style/missing.png"

  validates_attachment :avatar, :presence => true,
    :content_type => { :content_type => ["image/jpeg", "image/gif", "image/png"] },
    :size => { :in => 0..500.kilobytes }
end