Skip to content

Instantly share code, notes, and snippets.

@danielres
Created November 10, 2010 23:41
Show Gist options
  • Save danielres/671728 to your computer and use it in GitHub Desktop.
Save danielres/671728 to your computer and use it in GitHub Desktop.
how to have checkboxes in the view for a many-to-many relationship
# in controller:
def update
# (.....)
@categories = Category.all
checked_categories = []
checked_params = params[:category_list] || []
for check_box_id in checked_params
category = Category.find(check_box_id)
if not @texture.categories.include?(category)
@texture.categories << category
end
checked_categories << category
end
missing_categories = @categories - checked_categories
for category in missing_categories
if @texture.categories.include?(category)
@texture.categories.delete(category)
end
end
# (.....)
end
class Category < ActiveRecord::Base
has_and_belongs_to_many :textures
end
class Texture < ActiveRecord::Base
has_and_belongs_to_many :categories
end
<% # in view: %>
<% form_for(@texture) do |f| %>
<% #(.....) %>
<% for category in @categories %>
<%= check_box_tag(
'category_list[]',
category.id,
@texture.categories.collect {|obj| obj.id}.include?(category.id))
%>
<%= category.name %><br />
<% end %>
<% #(.....) %>
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment