我有一张有牢房的桌子。
如何使用cocoon创建一个表单,其中每个单元格
belongs_to行、列和表?
例如:
# Table
class Roster < ApplicationRecord
    has_many :timeslots, inverse_of: :roster
    has_many :games, inverse_of: :roster
    accepts_nested_attributes_for :timeslots, reject_if: :all_blank, allow_destroy: true
    accepts_nested_attributes_for :games, reject_if: :all_blank, allow_destroy: true
end
# Column
class Court < ApplicationRecord
  belongs_to :roster
  has_many :games
  accepts_nested_attributes_for :games, reject_if: :all_blank, allow_destroy: true
end
# Row
class Timeslot < ApplicationRecord
    belongs_to :roster
    has_many :games
    accepts_nested_attributes_for :games, reject_if: :all_blank, allow_destroy: true
end
# Cell
class Game < ApplicationRecord
    belongs_to :timeslot
    belongs_to :roster
end我现在尝试一个隐藏的<input>为每个游戏的:timeslot_id和:court_id,唯一的问题是,你不能得到的id之前,时间分配和法庭被保存。我要做的另一个想法是让每个游戏都有一个隐藏的行/列的<input>。
发布于 2017-03-15 03:46:21
我终于明白了:每个细胞都有两个隐藏的输入:
<%= cell.hidden_field :row %>
<%= cell.hidden_field :column %>单元格belongs_to关联必须是可选的:
class Cell < ApplicationRecord
    belongs_to :table
    belongs_to :column, optional: true
    belongs_to :row, optional: true
end该表有一个after_save回调:
after_save do |table|
    table.rows.each_with_index do |row,row_number|
        table.cells.each do |cell|
            if cell.row-1 == row_number
                cell.row = row
                cell.save()
            end
        end
    end
    table.columns.each_with_index do |column,column_number|
        table.cells.each do |cell|
            if cell.column-1 == column_number
                cell.column = column
                cell.save()
            end
        end
    end
end也许有更好的方法来做到这一点,但我认为这是最简单的。您需要在数据库中添加两个额外的列:row和column (主要缺点)
https://stackoverflow.com/questions/42758702
复制相似问题