2014-02-10 189 views
1

代碼從軌道的最佳實踐如何設置使用Ruby on Rails的

class TweetsController < ApplicationController 
    def index 
    @tweet = current_user.tweets.limit(10) 
    @trending = Topic.trending(5) 
    end 

    def retweet 
    tweet = tweet.find(params[id]) 
    flash[:notice] = tweet.retweet_by(current_user) 
    redirect_to tweet 
    end 
end 

class Tweet < ActiveRecord::Base 
    default_scope :recent.order('createted_at DESC') 
    # Overwrite the default scope 
    #@tweets = current_user.tweets.unscoped.order(:status).limit(10) 

    def retweet_by(retweeter) 
    if self.user == retweeter 
     "Sorry, you can't retweet you own tweet" 
    elsif self.retweets.where(user_id: retweeter.id).present? 
     "You already retweeted!" 
    else 
     s = tweet.new 
     s.status = "RS #{tweet.user.name}: #{tweet.status}" 
     s.original_tweet = tweet 
     s.user = current_user 
     s.save 
     "Succesfully retweeted" 
    end 
    end 
end 

我嘗試轉貼從上面的代碼我猜的模型添加到我的博客應用

模型Twitter的風格應是:

class CreateTweets < ActiveRecord::Migration 
    def change 
    create_table :tweets do |t| 
     t.string :status 
     t.integer :original_tweet 
     t.integer :user_id 

     t.timestamps 
    end 
    add_index :Tweets, [:user_id, :created_at] 
    end 
end  

和這條線

self.retweets.where(user_id: retweeter.id).present? 

給我的想法,應該有與user_ID的一個單獨的模型轉推和tweet_id

我怎麼可以設置查看該代碼轉推鏈接

回答

1

如果你想重新Twitter功能,你」 ð必須保持你的 「數據」 模式分離(usertweet):


模式

#app/models/user.rb 
Class User < ActiveRecord::Base 
    has_many :tweets 
end 


#app/models/tweet.rb 
Class Tweet < ActiveRecord::Base 
    belongs_to :author, class_name: "User", foreign_key: "user_id" 
    has_many :retweets, class_name: "Tweet", foreign_key: "retweet_id" 
end 

模式

users 
id | info | about | user | created_at | updated_at 

tweets 
#retweet_id for retweets 
id | user_id | retweet_id | status | created_at | updated_at 

這將使你打電話的東西,如:

@user.tweets.each do |tweet| 
    tweet.status 
    tweet.created_at 
end 

@tweet.author 

轉推

#config/routes.rb 
resources :tweets do 
    member do 
     post :retweet 
    end 
end 

#app/controllers/tweets_controller.rb 
def retweet 
    @retweet = Tweet.new(retweet_params) 
    @retweet.save 
end 

private 

def retweet_params 
    params.require(:retweet).permit(:retweet_id, :status).merge(user_id: current_user.id) 
end 

#app/views/tweets/show.html.erb 
<%= link_to tweet_retweet_path(tweet.id), method: :post %> 
+0

怎麼樣的看法,我怎麼建立轉推鏈接 –

+0

嘿,夥計,正想寫的更新你 - 但必須完成一些工作,我整理出來的!我已經提供了更新 –

+0

謝謝,這正是我需要的。 –