[英]How to setup a model twitter style using ruby on rails
Code from rails best practices 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
I am trying to add reshare to my blog app 我正在尝试将转发添加到我的博客应用中
from the above code I am guessing the model should be: 从上面的代码中,我猜模型应该是:
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
and this line 这条线
self.retweets.where(user_id: retweeter.id).present?
give me the idea that there should be a separate model retweet with user_id and tweet_id 让我想到应该使用user_id和tweet_id单独转发模型
how can I set up view for this code with retweet link 如何使用转推链接为此代码设置视图
If you're trying to recreate Twitter functionality, you'd have to keep your "data" models separate ( user
and tweet
): 如果您想重新创建Twitter功能,则必须将“数据”模型分开(
user
和tweet
):
Models 楷模
#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
Schema 架构
users
id | info | about | user | created_at | updated_at
tweets
#retweet_id for retweets
id | user_id | retweet_id | status | created_at | updated_at
This would allow you to call things like: 这将使您可以调用以下内容:
@user.tweets.each do |tweet|
tweet.status
tweet.created_at
end
or 要么
@tweet.author
Retweet 转推
#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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.