视图:
<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
endkitchen.rb
class Kitchen < ApplicationRecord
belongs_to :user
has_one :picture, as: :imageable, dependent: :destroy
accepts_nested_attributes_for :picture
endpicture.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我想要多态图片模型。我决定处理多态图片关联,但它总是回滚.卡住了。我已经把控制台上的图像附加了。谢谢!!使用binding.pry调试它
发布于 2017-02-14 18:27:55
在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发布于 2017-02-14 11:28:30
imageable在image.rb中的验证存在一个问题
当你把厨房和图像一起储存在一起时,一次就可以了。由于厨房尚未创建,图像的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这些关联是相反的,所以如果设置了这些关联,就不要进行查询来获取其他关联。
这样,如果设置任何关联,则其他关联将自动设置,验证不会失败。
这里是一个很好的inverse_of使用博客。
https://stackoverflow.com/questions/42215758
复制相似问题