I'm trying to show all the posts that I like by current user.
I'm using Ruby on Rails, and the gems Devise and "Acts As Votable". I've been following the Acts As Votable guide but can't make it work.
I think this is the way to go:
@post.liked_by @user1
@post.downvote_from @user2
I created a new controller called dashboard:
class DashboardController < ApplicationController
def index
@post = Post.all.liked_by current_user
end
end
But when I run my web I get:
undefined method `liked_by' for #<Post::ActiveRecord_Relation:0x9aa89b0>
What can I do?
The issue is that you're calling it on an ActiveRecord Relation, not on the model object, itself. A couple of minor changes, and you'll be all set.
First, we make the instance variable plural to show that it's receiving multiple records (a user can like multiple posts):
class DashboardController < ApplicationController
def index
@posts = Post.all.liked_by current_user
end
end
Then, to process these, you'll want to navigate to the individual record or records. If you want to process the whole list, you can do this:
@posts.each do |post|
post.liked_by @user1
post.downvote_from @user2
end
This will apply the like and downvote to all of the posts. However, you can update only the first post, like this:
post = @posts.first
post.liked_by @user1
post.downvote_from @user2
If you already knew what post you wanted to vote on (maybe based on which was chosen in the UI), you could do this:
@post = Post.find_by(params[:id])
@post.liked_by @user1
@post.downvote_from @user2
Making sure to keep your plural and singular names distinct will help you keep in tune with Rails conventions and will help you easily identify when you're working with a collection or an individual object.