作为一个背景,我制作了一个系统,注册用户可以在其中发布图形的赏金。他们说出他们想要的东西,并将其作为公众可见的赏金发布。用户也可以作为艺术家注册到系统中。Ruby on Rails使用单个表单为一个不同的类保存一个类的多个实例
但诀窍是,发布赏金的用户可以指定允许接受赏金的注册艺术家的子集。我想我需要做出通过表单的赏金是有帮助的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>
...
保存赏金类的新实例,这种方式很容易。但问题是我还想保存一个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作为我第一次参与开发,我很欣赏有这样的社区可以提供帮助。先谢谢你。