Skip to content

Instantly share code, notes, and snippets.

@mikefarmer
Created June 3, 2011 17:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikefarmer/1006755 to your computer and use it in GitHub Desktop.
Save mikefarmer/1006755 to your computer and use it in GitHub Desktop.
Snippets for Bookshelves
<%= form_for @bookshelf do |f| %>
<%= f.error_messages %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<% @books.each do |book| %>
<%= check_box_tag "books[#{book.id}]", "1", @bookshelf.books.include?(book) %>
<%= book.name %>
<br>
<% end -%>
<p><%= f.submit %></p>
<% end %>
class Book < ActiveRecord::Base
has_many :chosen_books
has_many :bookshelves, :through => :chosen_books
end
class Bookshelf < ActiveRecord::Base
has_many :chosen_books
has_many :books, :through => :chosen_books
end
# Note: inapplicable controller code omitted
def update
@bookshelf = Bookshelf.find(params[:id])
if @bookshelf.update_attributes(params[:bookshelf])
sync_selected_books
redirect_to @bookshelf, :notice => "Successfully updated bookshelf."
else
@books = Book.all
render :action => 'edit'
end
end
# ...
private
def sync_selected_books
if params[:books]
checked_books = Book.where(:id => params[:books].keys).all
current_books = @bookshelf.books
books_to_remove = current_books - checked_books
books_to_add = checked_books - current_books
ChosenBook.delete_all(:bookshelf_id => @bookshelf.id, :book_id => books_to_remove)
@bookshelf.books << books_to_add
else
ChosenBook.delete_all(:bookshelf_id => @bookshelf.id)
end
end
class ChosenBook < ActiveRecord::Base
belongs_to :book
belongs_to :bookshelf
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment