Question

I want to impliment something which is similar to Twitter Repost System, therefore I will use this as an example. So let's say I have a Tweet Model and I want to allow other user to repost a certian tweet of another user, how do I impliment something like this? I thought I would be a cool idea to put the retweet class into the tweet to be able to acess the repost too when I use Tweet.all to recive all tweets stored in the database, but somehow I didn't worked as expected... The following Code is just an example which should show how to impliment this even if it is not working... Any ideas how I could build a working repost model which also allows me to access both tweets and retweet by using Tweet.all?

class Tweet
  class Retweet
    include DataMapper::Resource

    belongs_to :user, key => true
    belongs_to :tweet, key => true
  end

  include DataMapper::Resource
  property :text, String
  property :timestamp, String

  belongs_to :user
end

Important: I should be carrierwave compatible.

Was it helpful?

Solution

class Tweet
  include DataMapper::Resource
  property :id, Serial
  has n, :retweets, 'Tweet', :child_key => :parent_id
  belongs_to :parent, 'Tweet', :required => false
  belongs_to :user

  def is_retweet?
    self.parent_id ? true : false
  end
end

original = Tweet.create :user => user1
retweet = Tweet.create :parent => original, :user => user2
retweet.is_retweet? # => true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top