Created
June 3, 2011 17:36
-
-
Save mikefarmer/1006755 to your computer and use it in GitHub Desktop.
Snippets for Bookshelves
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
<%= 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 %> |
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 Book < ActiveRecord::Base | |
has_many :chosen_books | |
has_many :bookshelves, :through => :chosen_books | |
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 Bookshelf < ActiveRecord::Base | |
has_many :chosen_books | |
has_many :books, :through => :chosen_books | |
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
# 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 |
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 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