Basic Rails Controller Methods and Params Handling
# /tweets?status=Message...
# params = {status: "Message..."}
@tweet = Tweet.create(status: params[:status])
# /tweets?tweet[status]=Message...
# params = {tweet: {status: "Message..."}}
@tweet = Tweet.create(status: params[:tweet][:status])
@tweet = Tweet.create(params[:tweet])
# Strong parameters required only for creating or updating
@tweet = Tweet.create(params.require(:tweet).permit(:status))
# For multiple params
params.require(:tweet).permit([:status, :location])
# Flash and redirect shortcut
redirect_to(tweets_path, notice: "You can't do that.")
# Keep tweet retrieval DRY
before_action :get_tweet, only: [:edit, :update, :destroy]
def get_tweet
@tweet = Tweet.find(params[:id])
end
# Keep user authorization DRY
before_action :check_auth, only: [:edit, :update, :destroy]
def check_auth
if session[:user_id] != @tweet.user.id
flash[:notice] = "You can't do that."
redirect_to tweets_path
end
end
# Display params in JSON and XML format
def show
@user = User.find(params[:id])
respond_to do |format|
format.html
format.json { render json: @user }
format.xml { render xml: @user }
end
end