Created
October 1, 2014 19:44
-
-
Save jasonblanchard/d01e2ea2231322ff8a1a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 ArticlesController < ApplicationController | |
| before_action :set_article, only: [:show, :edit, :update, :destroy] | |
| def index | |
| @articles = Article.all | |
| @articles_category = Article.order(:category) | |
| @users = User.all | |
| end | |
| def show | |
| # @article is available here because we are running the private | |
| # set_article method in the before action (actually defined below). This can feel a little magical, | |
| # but try setting up @article without the before action to see what's going on. | |
| # Remember that any instance variables we set here are accessible in the view | |
| # and we can basically add any code here: | |
| @cat_sound = "Meow" # You can now do <%= @cat_sound %> in the articles/show.html.erb view to print out "Meow" on the page. | |
| # Imagine we had articles on comments | |
| # @comments = Comment.where(:article_id => @article.id) | |
| # Or, even better: | |
| # @comments = @article.comments | |
| # We also have access to this mystical params hash: | |
| @article_id_we_care_about = params[:id] | |
| # Check out the rails server console output when you visit an article page to see where this is coming from. | |
| # The params hash comes from the parts of the url that scope a route or give you additional variables to use in the controller. | |
| # If you run rake routes in your project, you will see that there is probably a route that looks like this: | |
| # GET /articles/:id | |
| # Check out that last :id part. Look familiar? | |
| end | |
| private | |
| def set_article | |
| @article = Article.find(params[:id]) | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment