在Rails中,如何以嵌套形式创建新记录?

时间:2014-05-24 05:31:42

标签: ruby-on-rails forms activerecord ruby-on-rails-3.2 fields-for

我有一个由父模型Challenge和子模型ChallengeRoster组成的嵌套表单。在挑战的编辑页面中,我当前可以编辑/更新挑战的属性,并且可以编辑/更新当前存储的ChallengeRoster记录。但是,我想要的最后一步是通过选中所显示记录旁边的复选框,然后单击页面的表单提交按钮,还可以选择符合条件的记录来创建和存储在ChallengeRoster中。如果您查看下面的_form.html.erb文件,则问题在于第三个循环。现在我能够显示正确的contestant_id& challenge_id用于创建每个符合条件的记录,但我不知道如何显示复选框,并且只有在我按下表单后页面才会将所选记录添加到数据库中提交按钮。如果我忘记发布任何代码,请告诉我。

_form.html.erb

<%= form_for @challenge do |f| %>

   <%= f.label :name %><br />
   <%= f.text_field :name %><br />
   <%= f.label :description %><br />
   <%= f.text_field :description %>


   <%= f.fields_for :challenge_rosters do |builder| %>
      <%= builder.object.contestant.full_name %><br />
      <%= builder.check_box :active %><br />
      <%= builder.check_box :winner %>
   <% end %>


   <% @roster_options.each do |option| %>
     <%= f.fields_for :challenge_rosters, option do |roster_fields| %>
     <%= roster_fields.object.contestant.full_name %><br />
     <%= roster_fields.text_field :contestant_id %><br />
     <%= roster_fields.text_field :challenge_id %>
     # I want to put a checkbox here to determine which ones I want to add to challenge_rosters table
   <% end %>

   <%= f.submit %>

<% end %>

challenges_controller.rb

def edit

  @challenge = Challenge.find(params[:id])
  @challenge_roster = ChallengeRoster.where(challenge_id: params[:id])

  # I use the next ivar to get contestant_ids that aren't currently part of challenge_rosters, but that are eligible for this challenge
  @options = SeasonRoster.where("season_id = (?) AND NOT EXISTS ( SELECT * FROM challenge_rosters INNER JOIN challenges ON challenges.id = challenge_rosters.challenge_id WHERE challenge_rosters.contestant_id = season_rosters.contestant_id AND challenges.id = (?))", @challenge.season_id.to_s, @challenge.id.to_s)

  @roster_options = Array.new
  @options.each do |o|
    c = ChallengeRoster.new
    c.contestant_id = o.contestant_id
    c.challenge_id = params[:id]
    @roster_options.push(c)
  end

end

模型

challenge.rb

class Challenge < ActiveRecord::Base
  attr_accessible :name, :description, :challenge_roster_attributes
  has_many :challenge_rosters
  has_many :contestants, :through => :challenge_rosters
  accepts_nested_attributes_for :challenge_rosters, allow_destroy: true
end

challenge_roster.rb

class ChallengeRoster < ActiveRecord::Base
  attr_accessible :active, :winner, :contestant_id, :challenge_id
  belongs_to :challenge
  belongs_to :contestant
end

0 个答案:

没有答案