Created
November 10, 2010 23:41
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Category < ActiveRecord::Base | |
has_and_belongs_to_many :textures | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Texture < ActiveRecord::Base | |
has_and_belongs_to_many :categories | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<% # 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