【问题标题】:Ruby on Rails saving multiple instances of a class using a single form for a different classRuby on Rails 使用单个表单为不同的类保存一个类的多个实例
【发布时间】:2013-03-30 00:43:12
【问题描述】:

作为背景知识,我正在制作一个系统,注册用户可以在其中发布艺术品赏金。他们说出他们想要什么,并将其发布为公开可见的赏金。用户也可以作为艺术家注册到系统中。

但诀窍在于,发布赏金的用户可以指定允许接受赏金的注册艺术家的子集。我猜想通过表格获得赏金需要的是有用的form_for 工具...

<%= form_for @bounty do |bounty_form| %>
<div class="field">
    <%= bounty_form.label :name %>
    <%= bounty_form.text_field :name %>
</div>
<div class="field">
    <%= bounty_form.label :desc %>
    <%= bounty_form.text_area :desc %>
</div>
...

以这种方式保存 Bounty 类的新实例很容易。但问题是我还想同时保存 Candidacies 类的多个实例,这取决于用户在保存此赏金时(通过复选框)选择了哪些艺术家。因此,假设系统中只有 2 位艺术家,Artist1 和 Artist2,用户应该能够选择 1、2、两者都不选择,或者两者都选择,并且它应该与赏金一起创建候选人。

我知道accepts_nested_attributes_for,但它似乎对创建类的单个实例很有用,例如在保存人员对象时创建地址对象。我需要的是一种在单个表单提交上保存多个 (0-n) 类的方法。

这里有一些参考:

赏金只是名称、描述、价格……诸如此类。 form_for 最初是为这张表创建的。

# == Schema Information
#
# Table name: bounties
#
#  id             :integer          not null, primary key
#  name           :string(255)      not null
#  desc           :text             not null
#  price_cents    :integer          default(0), not null
#  price_currency :string(255)      default("USD"), not null
#  rating         :boolean          default(FALSE), not null
#  private        :boolean          default(FALSE), not null
#  url            :string(255)
#  user_id        :integer          not null
#  accept_id      :integer
#  reject_id      :integer
#  complete_id    :integer
#  created_at     :datetime         not null
#  updated_at     :datetime         not null
#

然后根据用户的提交,在保存赏金时需要填充这个小的多对多连接表。

# == Schema Information
#
# Table name: candidacies
#
#  id         :integer          not null, primary key
#  user_id    :integer          not null
#  bounty_id  :integer          not null
#  created_at :datetime         not null
#  updated_at :datetime         not null
#

class Candidacy < ActiveRecord::Base
  attr_protected :id, :user_id, :bounty_id

  #Many to many join table between user and bounty.
  belongs_to :user
  belongs_to :bounty

  validates :user_id, presence: true
  validates :bounty_id, presence: true
end

最后,系统中的艺术家由@artist 实例变量提供。

总而言之:我需要能够保存 (0-n) 个候选人以及一次保存赏金,最好使用 form_for。

总的来说,我对 Rails 和编程非常陌生。像许多人一样,我正在学习 rails 作为我第一次涉足开发,我很感激有这样的社区可以提供帮助。提前谢谢你。

【问题讨论】:

    标签: ruby-on-rails ruby object save form-for


    【解决方案1】:

    我需要的是一种在单个表单提交上保存多个 (0-n) 类的方法。

    茧宝石对于创建多个嵌套表单非常有帮助。它允许您添加一个按钮,该按钮允许用户单击以添加多个嵌套表单,因此他们可以在一次提交时创建任意数量的表单。它还允许他们在一次提交时根据需要删除它们。

    https://github.com/nathanvda/cocoon

    宝石“茧”

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-10
      • 1970-01-01
      • 1970-01-01
      • 2018-12-04
      • 1970-01-01
      相关资源
      最近更新 更多