mercredi 21 janvier 2015

How to use a form to add many children to parent of has_many through

I'm working on an exercise app, an element of which is that a User has_many WorkoutTypes (WoType in the code) (via a has_many :through relationship), and I'd like to build a form to add more than one of each WorkoutType to a given user.


I've currently got a checkbox form working to add singular, different children to a user:



<%= form_for(resource, as: resource_name, url: registration_path(resource_name), html: { method: :put }) do |f| %>
...
...
<div class="field">
<%= hidden_field_tag "user[wo_type_ids][]", nil %>
<%= WoType.all.each do |wo_type| %>
<%= check_box_tag "user[wo_type_ids][]", wo_type.id, @user.wo_type_ids.include?(wo_type.id), id: dom_id(wo_type) %>
<%= label_tag dom_id(wo_type), wo_type.wo %><br>
<% end %>
</div>
...
...
<div class="actions">
<%= f.submit "Update" %>
</div>
<% end %>


This means a user can edit their account to select one of each of, for example, run, gym, football; however, I'd like them to be able to select as many of each as they'd like though (i.e. a user have three 'runs'). Any idea how I could update the form to implement this?


Here's the abridged code for the models:



class User < ActiveRecord::Base
has_many :wo_types, through: :wocfgs
has_many :wocfgs, dependent: :destroy
end

class WoType < ActiveRecord::Base
has_many :wocfgs
has_many :users, through: :wocfgs
end

class Wocfg < ActiveRecord::Base
belongs_to :user
belongs_to :wo_type
end


Bonus points: the checkbox is currently printing all of the WorkoutTypes below it in the view and I've no idea why. Any clues how to get rid of this would be great! I can't post an image as I don't have the rep, but here's a link to a screenshot: http://ift.tt/1CaENHc.


Thanks in advance!





Aucun commentaire:

Enregistrer un commentaire