0

I'm able to display the votes user likes, but I don't know how to display the actual record of the liked record. Whats the simplest way to retrieve user voted records?

controller.rb

def show
  @user = User.find(params[:id])
  @liked = @user.votes
end

show.html.haml

= @liked.to_json

Result:

[{"id":5,"votable_id":8,"votable_type":"Post","voter_id":2,"voter_type":"User","vote_flag":true,"vote_scope":null,"vote_weight":1,"created_at":"2016-02-01T00:33:15.968Z","updated_at":"2016-02-01T00:33:15.968Z"}]

How do I turn this so I can just display the title, description, etc... from the Post record?

hellomello
  • 8,219
  • 39
  • 151
  • 297

2 Answers2

0

Does the vote have post_id ? I assumed you have vote.rb and post.rb model.

vote.rb

belongs_to :post

post.rb

has_many :votes

In show

- @liked.each do |l| 
  = l.post.title 
  = l.post.description 
hellomello
  • 8,219
  • 39
  • 151
  • 297
Gold-Banana
  • 25
  • 1
  • 4
0

You've probably found the answer by now—but here's what I do to show a list of things a user has voted on using the acts_as_votable gem. I am using Devise, so I am using current_user to specify the currently logged in User in the controller.

controller.rb

@liked_posts = current_user.get_up_voted(Post)

view.html.erb

<h3>Your 'liked' blog posts</h3>
<% @liked_posts.each do |post| %>
    <p><%= link_to post.title, post %></p>
<% end %>

You can have as many of those as you want—to display a collection of things a user has 'liked' across your application:

@liked_quotations = current_user.get_up_voted(Quote)
@liked_comments = current_user.get_up_voted(Comment)
@liked_stories = current_user.get_up_voted(Story)

Then, loop through those to show each collection.

There are two other methods that might be helpful—one to collect all voted-on things and another to collect all down-voted things:

current_user.get_voted(Post)
current_user.get_down_voted(Post)
backwardm
  • 309
  • 3
  • 6