Rails Controllers Flashcards
controller index (without views)
def index
books = Book.all
render json: books
end
controller show (without views)
def show
book = Book.find_by(id: [params[:id])
render json: book
end
How do you check what routes are available?
bundle exec rake routes
What do I do when I want something to be the VIEW of an index controller action?
app/views/books/index.html.erb
its going to be an html file, and erb is embedded ruby code.
controller index (with views)
def index
@books = Books.all #this allows me to call the @books instance variable. we can do this b/c of erb.
render ‘index’ #this renders a template
end
How do we write ruby code that not be printed in the erb?
shortcut in atom: - tab
How do we write ruby code that will be printed in the erb?
shortcut in atom: = tab
How to show each book in <ul> in erb?</ul>
<ul>
<li>
</ul>
</li></ul>
controller show (with views)
def show
@book = Book.find_by(:id, params[:id]) #because we want to access it in the html.erb
render :show
end
What do I do when I want something to be the VIEW of an SHOW controller action?
show.html.erb
What if we don’t find the book we are trying to show?
def show
@book = Book.find_by(:id, params[:id]) #because we want to access it in the html.erb
if @book
render :show #packages up our response and give back to the cleint
else
render :index
redirect_to ‘/books’ #its in our routes!
#hey, make a new request.
end
end
How many redirects can we have in a method?
One. Redirect does not end execution of your meothd. Might get a double render error.
What does a template missing error mean?
We were able to find this controller action, but we couldn’t find a template.
New in views?
def new
render :new
end
new.html.erb
<h1> Add book to Library! </h1>
form action=”/books” method=”post”>
Title
new.html.erb and user’s info gets into the ??
<h1> Add book to Library! </h1>
form action=”/books” method=”post”>
Title
Example of a params hash-like object?
{“title” => “Harry Potter”, “controller” => “books”, “action”=>”create”}
Convention in terminal for generating a migration?
rails generate migration CreateTableName
When you create a model, is it plural or singular?
User (singular)
Inside a form, how do you create labels?
Title
Author
Year