Formtastic with Mongoid embedded_in relations

2019-04-16 10:53发布

问题:

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.