作为背景知识,我正在制作一个系统,注册用户可以在其中发布艺术品赏金。他们说出他们想要什么,并将其发布为公开可见的赏金。用户也可以作为艺术家注册到系统中。
但诀窍是允许发布赏金的用户指定允许接受赏金的注册艺术家的子集。我想我需要通过表格来获得赏金是有用的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 作为我第一次涉足开发,我很感激有这样的社区可以提供帮助。先感谢您。