0

一个属性有多个图片。表单中上传的图像应该可以通过 Property 类访问。

//Picture Model
class Picture < ApplicationRecord
  belongs_to :property
  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

//Property Model
class Property < ApplicationRecord
  has_many :pictures, dependent: :destroy
  accepts_nested_attributes_for :pictures
end

//Form
<%= form_for @property, :html => {multipart: true} do |f| %>
  <%= f.fields_for :pictures do |ph| %>
    <%= ph.file_field :image, as: :file %>
  <% end%>
<% end%>

//Properties Controller
def new
  @property = Property.new
  @property.pictures.build
end

def create
  @property = current_user.properties.build(property_params)
  @property.seller = User.find(current_user.id) # links user to property via. user_id
  respond_to do |format|
    if @property.save
      format.html { redirect_to @property, notice: 'Property was successfully created.' }
      format.json { render action: 'show', status: :created, location: @property }
    else
      format.html { render action: 'new' }
      format.json { render json: @property.errors, status: :unprocessable_entity }
    end
  end
end

提交表单时收到错误:图片属性必须存在

4

1 回答 1

0

在 Rails 5 中,belongs_to 会自动验证是否存在。您可以添加optional: true到 belongs_to:

class Picture < ApplicationRecord
  belongs_to :property, optional: true
end

或者您必须在创建图片之前保存属性:

编辑:在创建图片之前保存属性的简单方法

# PropertyController
def create
  @property = current_user.properties.build(property_params)
  @property.seller = User.find(current_user.id) # links user to property via. user_id
  respond_to do |format|
    if @property.save
      @property.picture.create(picture_params)
      format.html { redirect_to @property, notice: 'Property was successfully created.' }
      format.json { render action: 'show', status: :created, location: @property }
    else
      format.html { render action: 'new' }
      format.json { render json: @property.errors, status: :unprocessable_entity }
    end
  end
end

def picture_params
    params.require(:property).permit(:picture)
end
于 2017-06-18T02:20:35.433 回答