Formtastic与Mongoid embedded_in的关系

时间:2010-12-22 07:40:07

标签: ruby-on-rails mongoid formtastic

有没有快速的方法为embeds_many-embedded_in关系制作表单? 我有以下内容:

class Team
  include Mongoid::Document
  field :name, :type => String
  embeds_many :players
end

class Player
  include Mongoid::Document
  embedded_in :team, :inverse_of => :players
  field :name, :type => String
end

我想为团队创建一个表格,为玩家提供嵌入式编辑。在那里看到https://github.com/bowsersenior/formtastic_with_mongoid_tutorial但是“TODO”。

1 个答案:

答案 0 :(得分:5)

我写了formtastic_with_mongoid_tutorial,遗憾的是我还没有想出一个处理嵌入式关系的简单方法。我现在正在做的是在控制器中构建嵌入对象,然后将对象传递到块中。看起来有点像这样:

= semantic_form_for @team do |form|
  = @team.players.each do |player|
    = form.inputs :for => [:players, player] do |player_form|
      = player_form.input :name

不要忘记在Team中处理嵌套属性:

class Team
  include Mongoid::Document
  accepts_nested_attributes_for :players, 
    :allow_destroy => true, 
    # formtastic sends blank attributes to Mongoid models if you use checkboxes
    :reject_if => proc { |attributes| 
      attributes['name'].blank? && attributes['_destroy'].blank? 
    }
   # ...
end

绝对不是理想的。希望我能得到更多帮助,但也许这会指出你正确的方向。我会密切关注更好的解决方案,并在我找到任何内容时更新教程。