Skip to content

Instantly share code, notes, and snippets.

@rkjha
Last active December 20, 2015 10:38
Show Gist options
  • Save rkjha/6116761 to your computer and use it in GitHub Desktop.
Save rkjha/6116761 to your computer and use it in GitHub Desktop.
Library, Shelf and Book Model using Ruby/Active Record (in a typical ruby/rack application)
class Book < ActiveRecord::Base
attr_accessible :title, :author, :lang, :genre, :shelf_id
belongs_to :shelves
def enshelf shelf_id
@book.shelf_id = shelf_id
end
def unshelf
# setting shelf_id to nil means book is not on the shelf
@book.shelf_id = nil
end
end
class Library < ActiveRecord::Base
has_many :shelves
def count_shelves
@no_of_shelves = Shelf.find(:all)
end
def all_books
@all_books = Book.find(:all)
end
end
class Shelf < ActiveRecord::Base
attr_accessible :library_id
has_many :books
def list_books
@shelf_books = Book.where(:shelf_id => @shelf.id)
end
### sample examples for getting the list for a self e.g self no. 2 ###
# @shelf = Shelf.find(:shelf_id => 2)
# @shelf.list_books
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment