1

I have an app that is intended to sort all user articles by identical user fields. An example of this is if a user wanted to see all other user articles from users with a similar occupation. Each user has an occupation (string) field in the database. I've been able to filter all users with identical occupations by using this query:

similar_users = User.where(occupation: current_user.occupation)

I have been unsuccessful at filtering their articles by similar_users. Articles have an author_id which is equal to the user.id.

I've tried chains such as Articles.similar_users, Articles.similar_users.where(author_id: user.id), or Article.all.where(author_id: similar_users.id), but they don't work and rightly so. How would I go about chaining these classes? Is there more effective way, such as using named scopes with lambdas?

In Article.rb

  belongs_to(
  :user,
  class_name: "User",
  foreign_key: :author_id,
  primary_key: :id
  )

In User.rb

has_many(
:articles,
class_name: "Article",
dependent: :destroy
)
0

1 Answer 1

2

You have to something like

Article.includes(:user).where("users.occupation = ?", current_user.occupation)
Sign up to request clarification or add additional context in comments.

12 Comments

Have you ever heard about SQL injections?
Yes, I have, but I avoided them because I've heard they pose security threats if someone was able to inject their own code.
@VictorMoroz let me know how could you possibly break the above generated sql. I haven't consider anything like data is coming from user-input or so. I would update the answer or delete it. thanks
I tried that code on another repository that functions identically, but with Post instead of Article and I got this error #<#<Class:#<ActiveRecord::Relation::ActiveRecord_Relation_Post:0x0000010475d0a0>>:0x823ae850>
Rule of thumb is to assume that string fields can always come from user input. Use placeholders (? or :name), they were created for a reason.
|

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.