2017-08-09 105 views
1

我有軌4.1問題和答案論壇,其反應的客戶,用戶可以創建問題,答案和評論。我想通過使用活動模型串行器來傳遞所有用戶活動(不管類型)。理想情況下,這應該是一個由created_at排序的對象數組。我能夠創建數組,但推式方法會覆蓋另一個。結合用戶擁有的對象

我覺得我可能需要實際使用散列以避免嵌套的個體對象數組內的屬性的工作,但希望一些指導的迷宮。

如果這沒有意義,想想Facebook的顯示你最近的活動:

[ 
    "You posted 'It's my birthday!' on 08/04/2017", 
    "You liked Tammy's post on 8/3/2017", 
    "You commented on Rihanna Tweets as Motivational Posters page on 8/1/2017" 
] 

user_activity方法:

def user_activity 
    activity = [] 

    self.object.questions.each do |question| 
    activity.push(question) 
    end 

    self.object.answers.each do |answer| 
    activity.push(answer) 
    end 

    self.object.comments.each do |comment| 
    activity.push(comment) 
    end 

end 

感謝和抱歉noob問題。

+0

你'user_activity'必須在最後返回'activity'陣列 - 而且,我認爲使用AM ::串行是矯枉過正,你的情況,因爲你只想輸出字符串(而不是序列記錄到一個特定的對象,就像一個哈希)。需要這種與用戶活動兼容(=字符串)輸出的每個模型中包含的簡單模塊就足夠了。我可以提供關於如何實現這一目標 – MrYoshiji

+0

活泉一個例子!謝謝@MrYoshiji。我知道這是愚蠢的,我忘記了。按預期工作!謝謝! –

+0

我認爲,我們已經結婚了在這一點上AMS,但我不會介意的額外信息。我們實際上是序列化非用戶對象中的很多記錄。 –

回答

0

模塊實現:

module UserActivityOutputer 
    def output_for_user_activity 
    raise NotImplementedError, "You must implement `#{self.class}##{__method__}`" 
    end 
end 

模塊包括:

class Post 
    include UserActivityOutputer 
    def title ; 'combining user owned objects in rails' ; end # only here for easy copy-paste test in IRB 
    def created_at ; DateTime.now ; end # only here for easy copy-paste test in IRB 

    def output_for_user_activity 
    "You posted '#{self.title}' on #{I18n.l(self.created_at.to_date)}" 
    end 
end 

class SomeModel 
    include UserActivityOutputer 
    # did not implement output_for_user_activity method for example purpose 
end 

用法:

Post.new.output_for_user_activity 
# => "You posted 'combining user owned objects in rails' on 2017-08-09" 
SomeModel.new.output_for_user_activity 
# => NotImplementedError: You must implement `SomeModel#output_for_user_activity` 

您可以複製粘貼都在剛剛打開IRB控制檯這裏給出的代碼的(可能會重新定義現有PostSomeModel類),並看到OUTP UT。

這是一個非常基本的實現,只意味着定義「這個記錄應該輸出什麼」。它不支持排序,這將在其他地方。

+0

確實。只是好奇你爲什麼更喜歡使用AMS。我們通過序列化程序傳遞所有其他內容,並且只能在客戶端使用此「活動列表」。它不會作爲用戶模型或類似的單獨列保存。 –

相關問題