父母和所有孩子在关系中的单身形式?

时间:2012-05-02 04:42:54

标签: ruby-on-rails ruby nested-attributes

在我的RoR中,我有一个表gamesstatsplayers。每个游戏都有很多players,每个玩家都有很多“统计数据”,每个游戏都有很多statsplayers.我希望能够做的就是在我的编辑游戏表单上,我希望有一排字段来添加一个新的统计行,每个玩家都有一个。我已经阅读了很多关于nested_attributes的内容,但是找到了新的好资源如何完全做到这一点。

2 个答案:

答案 0 :(得分:1)

更新:以下是基于您在评论中说明的新关联的更新课程集

# models/game.rb
class Game < ActiveRecord::Base
  has_many :teams
  accepts_nested_attributes_for :teams
  attr_accessible :name, :teams_attributes
end

# models/team.rb
class Team < ActiveRecord::Base
  belongs_to :game
  has_many :players
  accepts_nested_attributes_for :players
  attr_accessible :name, :players_attributes
end

# models/player.rb
class Player < ActiveRecord::Base
  belongs_to :team
  has_many :stats
  accepts_nested_attributes_for :stats, reject_if: proc { |attributes| attributes['name'].blank? }
  attr_accessible :name, :stats_attributes
end

# models/stat.rb
class Stat < ActiveRecord::Base
  belongs_to :player
  attr_accessible :name
end

# controllers/games_controller.rb
class GamesController < ApplicationController
  def edit
    @game = Game.find(params[:id])
    @game.teams.each do |team|
      team.players.each do |player|
        player.stats.build
      end
    end
  end

  def update
    @game = Game.find(params[:id])
    if @game.update_attributes(params[:game])
      render "show"
    else
      render text: "epic fail"
    end
  end
end

# games/edit.html.erb
<%= form_for @game do |f| %>
  <%= f.fields_for :teams do |tf| %>
    <p>Team: <%= tf.object.name %></p>
    <%= tf.fields_for :players do |pf| %>
      <p>Player: <%= pf.object.name %></p>
      <%= pf.fields_for :stats do |sf| %>
        <%= sf.text_field :name %>
      <% end %>
    <% end %>
  <% end %>
  <%= f.submit %>
<% end %>

注意这不会做任何类型的ajax“添加另一个stat”或任何花哨的东西。它只为每个玩家在最后添加一个空白区域。如果你需要更多,你可以在GamesController#edit动作中构建更多空白的统计对象,或者实现一些花哨的裤子javascript。希望这能让您足够接近,以便能够让您的实际数据正常运行。

答案 1 :(得分:0)

http://railscasts.com/episodes/196-nested-model-form-part-1

http://railscasts.com/episodes/197-nested-model-form-part-2

没有看到更多你自己的代码,我不能具体,但基本上,你循环所有玩家并“建立”统计数据... game.players.each {| p | p.build_stat}然后在表单中,再次循环遍历所有玩家,并显示统计数据(可能限制为new_record?那些?)或者也许在表单中进行构建,以便显示空白条目。

我认为我看到了一个潜在的问题,你的模型......如果统计数据是特定游戏的特定表现形式,那么你所描述的模型不会链接它们 - 你需要一个game_id和每个统计记录中的player_id。如果是这种情况,您将在控制器方法中构建所有统计信息,并在视图中循环它们。

相关问题