我看到一个类似的回答问题here让我走得这么远。但现在我在Form中遇到错误。我正在寻找的解决方案基本上是保存到Ruby Rails中的两个表,其中在第一个表中保存带地址的Property也可以在Pictures的第二个表中保存2个图像。
Migration1:
class CreateProperties < ActiveRecord::Migration[5.0]
def change
create_table :properties do |t|
t.string :address
t.timestamps
end
end
end
Migration2:
class CreatePictures < ActiveRecord::Migration[5.0]
def change
create_table :pictures do |t|
t.string :image1
t.string :image2
t.timestamps
end
end
end
物业模型:
class Property < ApplicationRecord
has_many :pictures
accepts_nested_attributes_for :pictures
end
图片模型:
class Picture < ApplicationRecord
belongs_to :property
end
PropertiesController:
class PropertiesController < ApplicationController
before_action :set_property
def new
@property = Property.new
end
def create
@property = properties.build(property_params)
if @property.save
flash[:success] = "Property was successfully created"
redirect_to property_path(@property)
else
render 'new'
end
end
private
def property_params
params.require(:property).permit(:address, picture_attributes: [:image1, :image2])
end
end
我不知道的表格如下:
<%= form_for(@property) do |f| %>
<%= f.label :address %>
<%= f.text_field :address %>
<%= f.label :image1 %>
<%= f.text_field :image1 %>
<%= f.label :image2 %>
<%= f.text_field :image2 %>
<%= f.submit %>
<% end %>
错误图片:
答案 0 :(得分:2)
您应该使用fields_for
方法在属性表单中包含图片表单:
# inside the property form_for
<%= f.fields_for @property.pictures.build do |p| %>
<%= p.file_field :image1 %>
<%= p.file_field :image2 %>
<% end %>