Answer the question
In order to leave comments, you need to log in
How to write a query in rails to pull certain records from the database?
In general, the situation is this, I want to pull out users with a specific role from users, but I don’t know how to write .joins queries correctly, please share your experience.
class UsersController < ApplicationController
def index
@users = User.all
@users.roles.where(role: 4)
end
end
class User < ActiveRecord::Base
has_many :users_roles, dependent: :destroy
has_many :roles, :through => :users_roles
class Role < ActiveRecord::Base
has_many :users_roles
has_many :users, :through => :users_roles
end
class UsersRole < ActiveRecord::Base
belongs_to :user
belongs_to :role
end
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question