2013-10-16 61 views
0

我爲我的應用程序創建了轉推/回覆功能。我應該如何去隱藏視圖中重複的「內容」?我在索引視圖中設置了它,以便顯示錶<%= render @letsgos %>中的所有條目。在視圖中隱藏數據庫中的重複內容

我設置了轉推/回覆,以便用戶B可以轉發用戶A發佈的內容。在數據庫中,它將複製用戶A的原始發佈內容,並在「repost_from_user_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 

回答

2

如果我理解正確的話,你不想顯示轉播(或原件)。您應該在索引中使用範圍或方法。
因此,而不是:

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 

在您的轉發方法中。

+0

謝謝。我寫了類似的東西,但不完全。這個答案很基本,所以我應該得出這個結論。謝謝您的幫助!!我只需要顯示原文。你有很大的幫助 –