一个属性有多个图片。表单中上传的图像应该可以通过 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
提交表单时收到错误:图片属性必须存在