Using Acts As Votable for multiple database tables with Rails 5

160 Views Asked by At

I have been using https://github.com/ryanto/acts_as_votable gem as a Save button for Posts. It has been all good so far.

However now I created a separate scaffold (Articles) and wanted to add the same Save button. So users can save Posts and Articles, then view in their profiles.

Now I got problem as some Article records has same id as Post records. Plus how do I even display Saved records now as I dont know what id comes from Article or Post.

Is there any way to solve this with Acts As Votable Gem?

Thank you!

1

There are 1 best solutions below

0
InsolentWorm On

The current version (0.12.0) of acts_as_voteable does this out of the box. The Vote model has a column votable_type which can be a reference to multiple models.

 #<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>

To display saved records you can use a scope like

@user.votes.for_type(Post)
@user.votes.for_type(Article)

I hope this answers your question.