Skip to content

Instantly share code, notes, and snippets.

@lilliealbert
Last active December 18, 2015 22:19
Show Gist options
  • Save lilliealbert/5854067 to your computer and use it in GitHub Desktop.
Save lilliealbert/5854067 to your computer and use it in GitHub Desktop.

ActionController

What is it?

  • It's a class --- and requests to the controller are just instances of the class
  • Controllers are responsible for doing one of two things
  • rendering something or redirecting to another URL
  • Sinatra v. Rails
  • The bulk of what you'd put in sinatra routes, are written in methods within the controller

Default Methods

  • index
  • new
  • create
  • update
  • delete
  • show
  • edit

Routes - what are they?

  • rake routes v. sinatra index.rb
  • break out your routes into controllers
  • route resources :users
  • possibly show a complete rails app

Filters:

Before filters run on requests before the request get to the controller's actions.

So, authenticate before granting access to do something — the perfect before filter opportunity!

After filter runs after, duh. They can modify responses, like if you need to send an email after a user has taken an action.

  • before_filters
  • after_filters
  • around_filters

LEARNING OPPORTUNITY: Shadi, want to explain around filters!?!

Params

  • pretty much the same as sinatra

Sessions & Cookies

  • Rails apps have a session for each user:
  • Only available in the view and the controller
  • Sessions ID's are always stored in the cookie, you should never pass sessions thru a URL

Session Storage:

  • ActionDispatch::Session::CookieStore – Stores everything on the client.
  • ActiveRecord::SessionStore – Stores the data in a database using Active Record.
  • ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.
  • ActionDispatch::Session::MemCacheStore – Stores the data in a memcached cluster (this is a legacy implementation; consider using CacheStore instead).

You can configure where the session is stored with some code by creating a session_store.rb file

YourApp::Application.config.session_store :cookie_store, :key => '_your_app_session'

Accessing Sessions

  • Just like a hash:

  • i.e. if you wanna get anything or store anything in a session all you gotta do is session[:foobar] = "Neil"

    session[:foobar] == "Neil"?

Cookies:

  • like sessions, cookies work like hashes, you can store anything in them.

cookies[:foobar] = "foo"

cookies[:foobar] == "foo"?

Helper methods

  • Can be defined within the controller using the helper_method :method
  • Show examples
  • CSRF and protect_from_forgery
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment