Formtastic with Mongoid embedded_in relations

本小妞迷上赌 提交于 2019-12-12 09:22:32

问题


Is there any quick way to make a form for embeds_many-embedded_in relation? I have the following:

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

I want to create a form for team with embedded editing for players. Seen https://github.com/bowsersenior/formtastic_with_mongoid_tutorial but "TODO" there.


回答1:


I wrote the formtastic_with_mongoid_tutorial and unfortunately I haven't figured out an easy way of dealing with embedded relations yet. What I'm doing now is building the embedded objects in the controller, and then passing the objects into a block. It would look kind of like this:

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

Don't forget to deal with nested attributes in 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

It is definitely far from ideal. Wish I could be of more help, but maybe this will point you in the right direction. I'll keep an eye out for better solutions and update the tutorial if/when I find any.



来源:https://stackoverflow.com/questions/4507116/formtastic-with-mongoid-embedded-in-relations

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!