A
A
Adil12013-12-06 18:12:22
Ruby on Rails
Adil1, 2013-12-06 18:12:22

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

The roles were written specifically for cancan and devise.
And now I don’t know how to insert where on the Join table in the controller, I’m a noob in rails.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sl_bug, 2013-12-06
@Adil1

for example

User.includes(:users_roles).references(:users_roles).where(usesr_roles: { id: 1 })

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question