Ruby on Rails使用单个表单为不同的类保存类的多个实例

时间:2013-03-30 00:43:12

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

作为一个背景,我正在建立一个系统,注册用户可以发布艺术作品的赏金。他们说出他们想要的东西并将其作为公开发布的赏金张贴。用户也可以作为艺术家注册到系统中。

但诀窍在于,发布赏金的用户可以指定允许接受赏金的已注册艺术家的子集。我猜我需要通过表单获得赏金是有用的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作为我第一次涉足开发领域,我很欣赏有这样的社区可以提供帮助。提前谢谢。

1 个答案:

答案 0 :(得分:0)

  

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

cocoon gem对于创建多个嵌套表单非常有用。它允许您添加一个允许用户单击以添加多个嵌套表单的按钮,这样他们就可以在一次提交时创建尽可能多的内容。它还允许他们在一次提交时尽可能多地删除它们。

https://github.com/nathanvda/cocoon

gem“cocoon”