Reputation: 44066
I have a rails form for creating users with a hidden field:
= hidden_field_tag "user[site_ids][]", @current_site.id, :data => @current_site.id, :class => 'current_site_id'
which sets the site_id of the current_site.
I also have a few checkboxes that have all the sites listed:
- Site.all.each do |site|
%label.checkbox
= check_box_tag 'user[site_ids][]', site.id, false, :class => "sites_checkbox"
= site.name
The reason I have the hidden field is si if the user doesn't select any of the checkboxes that it will at least set the @current_site
.
I was thinking of using JQuery like this: if the user selects one of the checkboxes that I set the value to 999 which is not in the db:
$(".roles_selected").click(function() {
var selected = $(this).closest("label");
if (selected.attr("data") == 'superadmin') {
$('.current_site_id').val(999);
} else {
$('.current_site_id').val($('.current_site_id').attr('data'));
}
});
and in the controller maybe removing 999 from params[:user][:site_ids]
That seems so hackish... Any other ideas?
Upvotes: 1
Views: 131
Reputation: 1203
A more straightforward solution would be to set the default site in the create/update methods of your controller. For example, something like:
@user = User.new(params[:user])
@user.sites << @current_site if params[:user][:site_ids].empty?
Then you can get rid of the hidden field in your form and the jquery.
Upvotes: 5