0

I have this inside User model

def self.home_opinions (user) 
        home_opinions = user.opinions
        user.follows.find_each do |follow|
          home_opinions+=(follow.opinions)
        end
        home_opinions.order_by_most_recent
    end

I have this scope inside Opinion model

scope :order_by_most_recent, -> { includes(:author).order(created_at: :desc) }

It shows this error

undefined method `order_by_most_recent' for #<Array:0x00007eff64d076f8>

But when I try User.home_opinions(User.find(9)) inside rails console It works

I have two questions

  1. why It shows the error
  2. What are the best practices for this code maybe using includes?

1 Answer 1

1

.order_by_most_recent will only work on an ActiveRecord::Relation.

When you call home_opinions = user.opinions you get a relation object back.

The problem comes when you call

home_opinions += follow.opinions

That action converts the relation into an array, and then .order_by_most_recent is no longer available.

If you can, you should try and get all relevant opinions in a single ActiveRecord call. That way, you'll have an ActiveRecord::Relation object which you can chain with other scopes – plus, you can do everything in a fixed number of database calls, rather than an extra call for every member of the follows association.

Try something like:

opinion_owner_ids = [user.id] + user.follow_ids
home_opinions = Opinion.where(user_id: opinion_owner_ids)
home_opinions.order_by_most_recent
Sign up to request clarification or add additional context in comments.

4 Comments

def self.home_opinions (user) follows_ids = [] user.follows.find_each do |follow| follows_ids.push(follow.id) end ` ids = [user.id] + [follows_ids]` ` home_opinions = Opinion.where(author_id: ids)` home_opinions.order_by_most_recent ` end` I did that and works thank you!
Btw how to add multiple line code in a comment in stack overflow :D?
You shouldn't need to construct your own array of IDs by looping through user.follows. If you've declared has_many :follows in your User model, you will automatically get a method called follow_ids that includes all the ID records. Have a look at the Example section in the Rails docs.
Yes I did that and its working thanks again ids = [user.id] + user.follow_ids home_opinions = Opinion.where(author_id: ids) home_opinions.order_by_most_recent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.