I have a Rails App that lets Users register. Users can have several music styles that they’d like to follow (many-to-many association).
Now, when a new user gets to the form, he should have all music styles checked by default. But when the existing user comes back (the same form is used on the edit page), he should have only those music styles checked, that are enabled for his profile. I’d assume that this has to be set in the controller but how do I sett all music styles for the new user?
Here’s the code in the form:
<% MusicStyle.all.each do |m| %>
<%= check_box_tag('user[music_style_ids][]', m.id, @user.music_styles.include?(m)) %>
<label for="<%= m.id %>"><%= m.name %></label><br/>
<% end %>
Your help is much appreciated!
When creating
@user, you could add all music styles to the new record you build. This would cause your form to be populated correctly.Alternatively, you could use
@user.new_record?to determine if this is a new record, and generate your checkbox tag depending on that.