I
I
IvanN7772015-03-11 21:05:51
Ruby on Rails
IvanN777, 2015-03-11 21:05:51

Whether it is possible to make scope for association (or as that with to imitate)?

class User < ActiveRecord::Base
has_and_belongs_to_many :roles,  -> { uniq }
has_and_belongs_to_many  :additional_roles, :class_name => 'Role'

There are users and each has a role_id field, there is a separate Roles class.
I wanted to write a scope so that the selection was only if users.role_id and roles.id do not match. Something like user.additional_roles.roles
There was an idea to make a separate has_and_belongs_to_many :additional_roles connection and set a condition through finder_sql, but I didn’t quite understand how to get the current role_id from the user.
Nobody faced?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
vsuhachev, 2015-03-14
@IvanN777

The scope can be made for any SQL, but there is a reasonable convention - the scope should produce objects of the class in which it is defined. Those. in your case, you need to define the scope in the Roles class and pass the user for which you want to filter the roles as a parameter. Well, keep in mind that the scope is a class method and not an object.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question