Skip to content

Controllers In Rails (The big 7 CRUD)

richlewis14 edited this page Nov 7, 2012 · 12 revisions

Thought I would clarify what is a view and what is hidden by rails (process rather than a view) and the type of request each action performs

 def index
  This page is a view
  This page performs a GET request
  For Example #@books = Book.all (Gets all books)
  This means that you will be able to have access to all books in your view
 end


def show
This page is a view (can show a single book for example)
This page performs a GET request
For Example #@books = Book.find(params[:id]) (Returns the book by ID)
This means that you will be able to have access to a specific book in your view
end

def new
This page is a view (mostly returns a form for creating a new object (In this case a book)
This page performs a GET request (Gets the form)
for example #@book =Book.new

end

def create
This page is NOT a view- it handles a POST request (via the new method above)
@book = Books.new(params[:book])
if @book.save
  redirect_to my_books_path, :notice => "Book sucessfully created."
end
end



def edit
This page is a view(mostly returns a form to edit an object (a book in this example)
This page performs a GET request
@book = Book.find(params[:id])

end

def update
This is NOT a view
This  performs a PUT request to update the specific object (book in this case) 
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
 redirect_to my_book_path, :notice => "Successfully updated Book"
else
render :action => "edit"

end


def destroy
This is NOT a view
This performs a DELETE request to destroy the specific object (book in this case)
 @book = Book.find(params[:id])
@book.destroy 
redirect_to my_bookss_path, :notice => "Successfully deleted book"
 end