scottysmalls
scottysmalls

Reputation: 1251

Rows with at least one matched object through a 'has_many through' relationship

My Models are set up as follows:

class Record < ActiveRecord::Base
    belongs_to :activity
    has_many :codes, -> { order("codes.name") }, through: :activity

class Activity < ActiveRecord::Base
    has_many :activity_code_links
    has_many :codes, through: :activity_code_links
    has_many :records

class ActivityCodeLink < ActiveRecord::Base
    belongs_to :activity
    belongs_to :code

class Code < ActiveRecord::Base
    has_many :activity_code_links
    has_many :activities, through: :activity_code_links
    has_many :records, through: :activities

In a controller, i have an ActiveRecord Relation of records, @records. I would like my resulting @records to only contain Records that have a specific Code.

Currently, i am using the below solution; however it is not efficient and also returns an Array, not an ActiveRecord Relation:

  @records = @records.reject { |record| (record.codes & [code]).empty? }

Any help would be appreciated

Cheers

Upvotes: 0

Views: 62

Answers (2)

user3409950
user3409950

Reputation: 373

@records.joins(:codes).where(codes: {id: code.id})

Please note that if you don't need to use codes entities later you should use joins instead of includes since it won't instantiate ActiveRecord objects which adds overhead

Upvotes: 1

Jay-Ar Polidario
Jay-Ar Polidario

Reputation: 6603

@records = @records.includes(:codes).where(codes: {id: code.id})

Where code is a Code object which is the one you want to be filtered.

Upvotes: 0

Related Questions