Rails for Zombies 1 4 Controllers - mikesabat/LR_HF GitHub Wiki
Rails best practice: Keep all the model calls in the controller. You want to limit Ruby code in the view. When you set a variable in the controller, it should start with an @. That tells rails that you want to have access to this variable in the view.
Generally the methods in the controller will be named the same as a view page. If you'd like the method to point to a different view, you can point to that in the method.
render :action => "viewname" ---- will point to /app/views/viewname.html.erb
it seems like an action in a view page.
Parameters will pass values from the URL into the controller. Let's take the find(id) example. The URL will look like /tweets/1. In the controller instead of Tweet.find(1) you write it as Tweet.find(params[:id]) - this looks up the id that we want to access. The routes, which will look at in the future tell the app how to map the urls to fields.
A session is a per user hash.
if session[:zombie_id] != tweet.zombie_id
__redirect_to(tweets_path
____:notice => "You can't edit this tweet")
end
flash [:notice] -- a message to the user.
After we put the flash notice into the controller, we need to go in to the view to say that if the flash notice exists, we need to print it out.
<% if flash[:notice] %>
In the controller we need to set the authorization on a few different functions - edit, delete and update. In each of those methods we first call the tweet. To DRY this up, instead of calling it three times, we can create a new functions for find_tweet
def find_tweet [email protected](params[:id]) end
We can then make a 'before_filter' to call find_tweet for edit, delete and update and before_filter :find_tweet, :only => [:edit, :update, :destroy]
Let's do the same thing for authorization. First - wrap the session check in a method
def auth __if session[:zombie_id] != tweet.zombie_id
____redirect_to(tweets_path
______:notice => "You can't edit this tweet")
__end
end
Then, make a before_filter to run that method before calling (edit, update and destroy)
before_filter :auth, :only => [:edit, :update, :destroy]