Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
# A user has many tweets.. and sometimes we want to retweet.
class TweetsController < ApplicationController
def retweet
@tweet = Tweet.find(params[:id])
if @tweet.user == current_user
flash[:notice] = "Sorry, you can't retweet your own tweets"
elsif @tweet.retweets.where(:user_id => current_user.id).present?
flash[:notice] = "You already retweeted!"
else
t = Tweet.new
t.status = "RT #{@tweet.user.name}: #{@tweet.status}"
t.original_tweet = @tweet
t.user = current_user
t.save
flash[:notice] = "Succesfully retweeted"
end
render :show
end
end
# This is a good example where the logic belongs in a Model. So our controller turns into
class TweetsController < ApplicationController
def retweet
@tweet = Tweet.find(params[:id])
result_message = @tweet.retweet_by(current_user)
redirect_to(@tweet, :notice => result_message)
end
end
# And the logic moves to the Model.
class Tweet < ActiveRecord::Base
def retweet_by(current_user)
if self.user == current_user
"Sorry, you can't retweet your own tweets"
elsif self.retweets.where(:user_id => current_user.id).present?
"You already retweeted!"
else
t = Tweet.new
t.status = "RT #{self.user.name}: #{self.status}"
t.original_tweet = self
t.user = current_user
t.save
"Succesfully retweeted"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment