Reputation: 2914
I created a retweet/repin feature for my app. How should I go about hiding the duplicate 'content' in the view? I have it setup in the index view so that it shows all the entries from the table <%= render @letsgos %>
.
I setup the retweet/repin so that User B can repost what User A posted. In the database it will copy the original posting from User A, and in the column 'repost_from_user_id' it will show the original id of the 'content'.
controller:
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
model:
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
Upvotes: 0
Views: 106
Reputation: 151
If I understand correctly you do not want to show the reposts (or the originals). You should use a scope or where method in your index.
So instead of:
def index
@letsgos = Letsgo.all
@eat = Letsgo.where(:tag => 'Eat')
end
try:
def index
@letsgos = Letsgo.where("repost_from_user_id IS NULL").all
@eat = Letsgo.where(:tag => 'Eat')
end
This should only show the originals. Showing only the reposts is a harder because it isn't as easy to filter them out. You might have to add a column to your model to flag the original when it was reposted. something like:
self.reposted = true
self.save
in your repost method.
Upvotes: 2