Rails 用于添加/删除关联的表单
Rails forms for adding / removing associations
我想知道如何在表单中添加/删除关联。假设我有两个通过外键链接的模型
class Event < ActiveRecord::Base
has_and_belongs_to_many :participants
end
class Participant < ActiveRecord::Base
has_and_belongs_to_many :events
end
我已经创建了一些表格来编辑每个模型。但是,有没有办法使用表格 remove/add 参与者 from/to 一个讲座? (我想这需要一些 javascript 来添加/删除视图中的条目以及......)
您正在寻找的是 accepts_nested_attributes_for
和一些 js 魔法。 Ryan Bates 在他的一些免费剧集中完美地描述了这一点:
而here是本集的完整源代码。
也许你需要调整一些东西,因为它有点旧,例如用 :onclick
事件替换 link_to_function
一个简单的 link_to
,但我认为几乎所有其他东西都适用于 Rails4。
希望对您有所帮助!
我想知道如何在表单中添加/删除关联。假设我有两个通过外键链接的模型
class Event < ActiveRecord::Base
has_and_belongs_to_many :participants
end
class Participant < ActiveRecord::Base
has_and_belongs_to_many :events
end
我已经创建了一些表格来编辑每个模型。但是,有没有办法使用表格 remove/add 参与者 from/to 一个讲座? (我想这需要一些 javascript 来添加/删除视图中的条目以及......)
您正在寻找的是 accepts_nested_attributes_for
和一些 js 魔法。 Ryan Bates 在他的一些免费剧集中完美地描述了这一点:
而here是本集的完整源代码。
也许你需要调整一些东西,因为它有点旧,例如用 :onclick
事件替换 link_to_function
一个简单的 link_to
,但我认为几乎所有其他东西都适用于 Rails4。
希望对您有所帮助!