嵌套表单的解决方案 [英] Solution for nested form

查看:62
本文介绍了嵌套表单的解决方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经被这个问题困住了一段时间.

I have been stuck on this problem for a while.

需要使用自定义输入为比赛类别制作一个表单.它应该从 Information 表中获取所有值并构建输入,但棘手的部分是它应该保存到 Category_informations 表中.

Need to make a form for competitions category with custom inputs. It should take all values from Information table and build the inputs, but the tricky part is that it should be saved to Category_informations table.

class Competition < ApplicationRecord
  has_many :categories
  has_many :informations
end

class Category < ApplicationRecord
  belongs_to :competetion
  has_many :category_informations
  has_many :information, through: competition
end

class CategoryInformation
  belongs_to :catagory
  belongs_to :information
end

class Information < ApplicationRecord
  belongs_to :competetion
  has_many :category_informations
end

比赛 -> 名称

类别 -> 名称,competition_id

Category -> name, competition_id

信息 -> 姓名,比赛 ID

Information -> name, competition_id

Category_informations -> 值、category_id、information_id

Category_informations -> value, category_id, information_id

推荐答案

看看这个 gem:https://github.com/plataformatec/simple_form

Simple Form 旨在尽可能灵活,同时帮助您使用强大的组件来创建表单.

Simple Form aims to be as flexible as possible while helping you with powerful components to create your forms.

举个简单的例子:

class Machine < ActiveRecord::Base
has_many :parts , inverse_of: :machine
accepts_nested_attributes_for :parts
end

class Part < ActiveRecord::Base
# name:string
belongs_to :machine
end

通过这些模型,我们可以使用 simple_form 以单一形式更新机器及其相关部件:

With these models, we can use simple_form to update the machine and its associated parts in a single form:

<%= simple_form_for @machine do |m| %>
  <%= m.simple_fields_for :parts do |p| %>
  <%= p.input :name %>
  <% end %>
<% end %>

对于新"操作,从控制器构建嵌套模型:

For 'new' action, build the nested model from the controller:

class MachinesController < ApplicationController
  def new
  @machine = Machine.new
  @machine.parts.build
 end
end

来源:https://github.com/plataformatec/simple_form/wiki/Nested-模型

这篇关于嵌套表单的解决方案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆