嵌套形式的解决方案

时间:2019-04-02 12:39:08

标签: ruby-on-rails

我在这个问题上停留了一段时间。

需要使用自定义输入为竞争 类别创建表格。它应该从 Information 表中获取所有值并构建输入,但棘手的部分是应将其保存到 Category_informations 表中。

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

信息->名称,Competition_id

类别信息->值,类别ID,信息ID

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

看看这个宝石:https://github.com/plataformatec/simple_form

简单表单旨在在帮助您使用功能强大的组件创建表单的同时尽可能地灵活。

让我们举一个简单的例子:

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以单一形式更新机器及其相关部件:

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

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

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

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

相关问题