Home > database >  Ruby on Rails Active Records issue
Ruby on Rails Active Records issue

Time:10-12

The models in question are: User Followed

The "followeds" schema(or table) has "user_id" that is a reference to "users" table And it has "followed_id" that is an integer.

What I want to achieve: Inside my controller I want to select all the users that have an id corresponding to followed_id Something like

def index
  @users = User.all.where(something like =>  "user.id: followeds.followed_id")
end

Basically comparing the id for users table (user.id) to followeds.followed_id integers and if they match extract the record of the user.

CodePudding user response:

In your User model you should have:

# No idea what's the nature of the relationship between your models, but
# pick one of these two
has_many :followeds, foreign_key: :followed_id
has_one :followed, foreign_key: :followed_id

then in your query call:

User.joins(:followeds) # or :followed if apply
  • Related