Roger Gonzalez
Roger Gonzalez

Reputation: 409

How can I filter a field from a Many To Many relationship in Rails?

I have the following tables scheme:

Table_1
    Name
    Field_A
    Field_B

User_Table
    Name
    Field_C
    Field_D

Table_3
    FK Table_1
    FK User_Table
    Field_E

All the relations work properly. I need to do something like this:

Table1.where(table_3.FK_Table_1: @current_user)

Basically, I just want to show the items that belong to the @current_user. I'm using my serializer to get all the Field_E that belongs to Table_1, but when I have 2 same items with the same Table_1, obviously it overwrites the value of Field_E. I want it to return all the items that are in Table_1 that also are from the @current_user

My current user is working correctly, so no worries with that. I just need help in how to achieve the where statement.

Any help would be appreciated

Upvotes: 0

Views: 920

Answers (2)

joeleba
joeleba

Reputation: 176

You can find out more about the has_many :through association from RoR guides:

class Table1 < ActiveRecord::Base
  has_many :table3s
  has_many :users, through: :table3s
end

class Table3 < ActiveRecord::Base
  belongs_to :table1
  belongs_to :user
end

class User < ActiveRecord::Base
  has_many :table3s
  has_many :table1s, through: :table3s
end

Then you can call @current_user.table1s to get all records in table1 that belongs to @current_user.

Note that using a join table (table3, in your case) implies a many-to-many relationship (1 table1 can belong to many users, 1 user can have many table1s).

Upvotes: 0

dodecaphonic
dodecaphonic

Reputation: 459

How are your models set up? From what you're describing, you need to specify that you're joining Table1 and Table3, and filtering by current user. Something like:

class Foo
  has_many :bars
end

class Bar
  belongs_to :foo
  belongs_to :user
end

# Joining and filtering
Foo.joins(:bars).where(bars: { user: @current_user })

Upvotes: 2

Related Questions