【发布时间】:2018-02-20 15:46:04
【问题描述】:
我遇到了嵌套表单的问题,我是 Rails 新手,所以可能我做错了什么,所以希望你能帮助我。提前致谢。
我有一个模型 Poi(兴趣点)、一个模型 PoiDescription 和一个模型 DescriptionType。 Poi 的一个实例有很多 PoiDescriptions,而一个 DescriptionType 有很多 PoiDescriptions。我想要的是:当我创建一个新的 Poi 时,我想为它创建多个描述。描述具有与之关联的类别,并且每个类别只能有一个描述(例如:10 个类别 = 10 个描述)。所以这是我的代码:
Poi 模型
has_many :poi_descriptions
accepts_nested_attributes_for :poi_descriptions
PoiDescription 模型
belongs_to :poi
belongs_to :description_type
描述类型模型
has_many :poi_descriptions
Poi 控制器
def new
@poi = Poi.new
@poi.poi_descriptions.build
@availableType = DescriptionType.where.not(id: @poi.poi_descriptions.pluck(:description_type_id))
end
def poi_params
params.require(:poi).permit(:name, :image, :longitude, :latitude, :monument_id, :beacon_id, poi_descriptions_attributes: [:description, :description_type_id, :id])
end
路线
resources :pois do
resources :poi_descriptions
end
resources :description_types
Poi _form
<%= form_with model: @poi do |f| %>
...
<%= f.fields_for :poi_descriptions do |p| %>
<%= p.collection_select :description_type_id, @availableType,:id,:name %>
<%= p.text_area :description %>
<% end %>
...
架构
create_table "description_types", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "poi_descriptions", force: :cascade do |t|
t.text "description"
t.bigint "poi_id"
t.bigint "description_type_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["description_type_id"], name: "index_poi_descriptions_on_description_type_id"
t.index ["poi_id"], name: "index_poi_descriptions_on_poi_id"
end
create_table "pois", id: :serial, force: :cascade do |t|
t.text "name"
t.float "longitude"
t.float "latitude"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.integer "monument_id"
t.integer "beacon_id"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.index ["beacon_id"], name: "index_pois_on_beacon_id"
t.index ["monument_id"], name: "index_pois_on_monument_id"
end
现在,问题来了。每次我尝试创建一个新的 Poi 时,我都会遇到这个错误: 有谁知道为什么会这样?谢谢。
P.S: 很抱歉发了这么长的帖子 :)
【问题讨论】:
标签: ruby-on-rails ruby nested-forms