使用Acts As Votable为多个数据库表使用Rails 5

时间:2018-06-12 10:25:59

标签: ruby-on-rails ruby-on-rails-5 multiple-tables acts-as-votable

我一直使用https://github.com/ryanto/acts_as_votable gem作为帖子的保存按钮。到目前为止一切都很顺利。

但是现在我创建了一个单独的脚手架(文章),并希望添加相同的保存按钮。因此,用户可以保存帖子和文章,然后在他们的个人资料中查看。

现在我遇到了问题,因为一些文章记录与Post记录具有相同的ID。另外,我现在如何显示已保存的记录,因为我不知道哪个ID来自文章或帖子。

使用Acts As Votable Gem有什么方法可以解决这个问题吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

acts_as_voteable的当前版本(0.12.0)开箱即用。 Vote模型具有一列votable_type,可以引用多个模型。

 #<ActsAsVotable::Vote:0x00007f9f6558a9b0
id: 4,
votable_type: "Post",
votable_id: 1,
voter_type: "User",
voter_id: 2,
vote_flag: true,
vote_scope: "save",
vote_weight: 1,
created_at: Mon, 31 Dec 2018 13:39:34 UTC +00:00,
updated_at: Mon, 31 Dec 2018 13:39:34 UTC +00:00>,

#<ActsAsVotable::Vote:0x00007f9f6558a4d8
id: 5,
votable_type: "Article",
votable_id: 3,
voter_type: "User",
voter_id: 2,
vote_flag: true,
vote_scope: "article",
vote_weight: 1,
created_at: Tue, 01 Jan 2019 15:15:27 UTC +00:00,
updated_at: Tue, 01 Jan 2019 15:15:27 UTC +00:00>

要显示已保存的记录,您可以使用类似

的作用域
@user.votes.for_type(Post)
@user.votes.for_type(Article)

我希望这能回答您的问题。