我为自己的应用创建了转推/回复功能。我该如何在视图中隐藏重复的“内容”?我在索引视图中进行了设置,以便显示表<%= render @letsgos %>
中的所有条目。
我设置了转推/回复,以便用户B可以重新发布用户A发布的内容。在数据库中,它将从用户A复制原始发布,在“repost_from_user_id”列中,它将显示“内容”的原始ID。
控制器:
class LetsgosController < ApplicationController
before_action :correct_user, only: :destroy
def create
@letsgo = current_user.letsgos.build(letsgo_params)
if @letsgo.save
flash[:success] = "Date posted!"
redirect_to root_url
else
flash[:error] = "Date was not posted!"
redirect_to root_url
end
end
def destroy
@letsgo.destroy
redirect_to root_url
end
def index
@letsgos = Letsgo.all
@eat = Letsgo.where(:tag => 'Eat')
end
def eatdrink
@eatdrink = Letsgo.where(:tag => 'Eat/Drink')
end
def listenwatch
@listenwatch = Letsgo.where(:tag => 'Listen/Watch')
end
def play
@play = Letsgo.where(:tag => 'Play')
end
def explore
@explore = Letsgo.where(:tag => 'Explore')
end
def other
@other = Letsgo.where(:tag => 'Other')
end
def repost
@letsgo = Letsgo.find(params[:id]).repost(current_user)
redirect_to root_url
end
private
def letsgo_params
params.require(:letsgo).permit(:content, :tag)
end
def correct_user
@letsgo = current_user.letsgos.find_by(id: params[:id])
redirect_to root_url if @letsgo.nil?
end
end
模型:
class Letsgo < ActiveRecord::Base
belongs_to :user
default_scope -> { order('created_at DESC') }
validates :content, presence: true, length: { maximum: 360 }
validates :user_id, presence: true
def repost(user_object)
new_letsgo = self.dup #duplicates the entire object, except for the ID
new_letsgo.user_id = user_object.id
new_letsgo.repost_from_user_id = self.id #save the user id of original repost, to keep track of where it originally came from
new_letsgo.save
end
def is_repost?
repost_from_user_id.present?
end
def original_user
User.find(repost_from_user_id) if is_repost?
end
end
答案 0 :(得分:2)
如果我理解正确,您不想显示转贴(或原件)。您应该在索引中使用范围或where方法 所以而不是:
def index
@letsgos = Letsgo.all
@eat = Letsgo.where(:tag => 'Eat')
end
尝试:
def index
@letsgos = Letsgo.where("repost_from_user_id IS NULL").all
@eat = Letsgo.where(:tag => 'Eat')
end
这应该只显示原件。仅显示转贴是更难的,因为过滤它们并不容易。您可能需要在模型中添加一列,以便在重新发布时标记原始列。类似的东西:
self.reposted = true
self.save
在你的转发方法中。