我在rails 4.1上有一个问答论坛,有一个react客户端,用户可以在其中创建问题,答案和评论。我想使用活动模型序列化程序传递所有用户活动(无论类型)。理想情况下,这应该是按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 :(得分: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控制台中复制粘贴此处显示的所有代码(可能会重新定义现有的Post
或SomeModel
类)并查看输出。
这是一个非常基本的实现,仅用于定义"应为此记录输出的内容" 。它不支持排序,这将在其他地方进行。