Sohn
Sohn

Reputation: 51

Rails order search results

I have a problem with ordering search results on rails. I want to order the posts after I searched or filtered but what I'm doing doesn't seem to work. Here is my code.

posts_controller.rb

display
  @posts = Post.where("user_id IN (?)", current_user.following_ids)
  @posts = @posts.find(Like.group(:post_id).pluck(:post_id)).order(params[:change]) if params[:change].present?
end

I have a posts_controller which displays the posts user are following to, it works fine. However, when I added an extra code trying to order the posts by the number of likes, error occurs. It seems that the second line in post controller extracts all the posts with like instead of only the posts the user are following. If I replace @posts.find with Post.find, all the posts result will be shown and ordered by the number of likes.

by the way, this, @posts.order(created_at: :desc), works fine. It orders only the posts user are following.

like.rb

class Like < ApplicationRecord
  belongs_to :post, foreign_key: "post_id"
  belongs_to :user
  validates_uniqueness_of :post_id, scope: :user_id
end

like_controller.rb

class LikesController < ApplicationController

def create
  @like = current_user.likes.create(post_id: params[:post_id])
redirect_back(fallback_location: root_path)
end

def destroy
  @like = Like.find_by(post_id: params[:post_id], user_id: current_user.id)
  @like.destroy
redirect_back(fallback_location: root_path)
end

end

I'm very new at programming so please forgive me if I'm asking a stupid question. Thank you all very much.

The error message is below:

enter image description here

Upvotes: 0

Views: 378

Answers (1)

lurker
lurker

Reputation: 58274

Note that find, when given an array, requires that all of the id's in the array be present or you get an error. In the documentation, it states:

If one or more records can not be found for the requested ids, then RecordNotFound will be raised.

I would use a different mechanism to retrieve the records:

@posts = @posts.where(id: Like.group(:post_id).pluck(:post_id)).
              order(params[:change]) if params[:change].present?

This will locate just those records that satisfy the condition.

This feels a little clunky. There might be a cleaner way of getting this result depending upon what relationship might exist in your models between Like, Post, and Group.

Upvotes: 1

Related Questions