I have this rails migration with the following code
class CreateCertificatesUsers < ActiveRecord::Migration[5.2]
def change
create_table :certificates_users do |t|
t.references :user, foreign_key: true
t.references :certificate, foreign_key: true
end
end
end
In Certificate model and User model, I have has_many :certificates_users
This allows me to be able to add a certificate to a user's profile. Currently, I have 2 users, and I have added Certificate for both of them.
2.5.3 :010 > CertificatesUser.all
CertificatesUser Load (0.6ms) SELECT "certificates_users".* FROM "certificates_users" LIMIT $1 [["LIMIT", 11]]
=> #<ActiveRecord::Relation [#<CertificatesUser id: 8, user_id: 1, certificate_id: 1, expiry_date: "2020-01-14", certificate_number: "1122", renewal_date: "2019-01-14", ispublic: 1>, #<CertificatesUser id: 9, user_id: 2, certificate_id: 1, expiry_date: "2020-01-16", certificate_number: "123", renewal_date: "2019-01-16", ispublic: 1>, #<CertificatesUser id: 10, user_id: 2, certificate_id: 2, expiry_date: "2019-02-28", certificate_number: "123", renewal_date: "2019-01-16", ispublic: 1>]>
Here is the certificates_users table for clarity.
id | user_id | certificate_id | ...
---+---------+----------------+----
8 | 1 | 1 |
9 | 2 | 1 |
10 | 2 | 2 |
One User has 2 certificates and the other has one.
My goal is to be able to list out Users who have a certain type of certificate.
- List out users who have a certificate with the id of 1 (should list out both users). - Dropdown 1
- List out only users who have both certificates with the id of 1 and certificate with the id of 2 (should list out only 1 user). - Dropdown 2
- When any of this user is selected from their separate dropdowns list out their certificate in another dropdown.
I have tried to use group
and group_by
to achieve this result but it did not work. The idea is that I am trying to group the CertificatesUser
by user_id
but that didn't work. It returned this error:
2.5.3 :011 > CertificatesUser.group_by(&:user_id)
Traceback (most recent call last):
1: from (irb):11
NoMethodError (undefined method `group_by' for #<Class:0x00007fa8dda7c668>)
Did you mean? group
Then I used group
method and got this:
2.5.3 :012 > CertificatesUser.group('users.id')
CertificatesUser Load (7.2ms) SELECT "certificates_users".* FROM "certificates_users" GROUP BY users.id LIMIT $1 [["LIMIT", 11]]
Traceback (most recent call last):
ActiveRecord::StatementInvalid (PG::UndefinedTable: ERROR: missing FROM-clause entry for table "users")
LINE 1: ...cates_users".* FROM "certificates_users" GROUP BY users.id L...
^
: SELECT "certificates_users".* FROM "certificates_users" GROUP BY users.id LIMIT $1
Any idea how I can make this work?