Is there a way to use two values in an association to restrict the data set instead of only one?
I have an has_many association of model Nyaw in a model Foo, which should be mapped using two values instead of just one.
I tried the following code, but it seems to fail to undefined method 'another_id' for #<Nyaw::ActiveRecord_Relation:0x00000003ee6f80> (NoMethodError) error:
class Foo < ActiveRecord::Base
has_many :nyaws, -> { where "another_id = ?", self.another_id }
end
self.another_id would be a value from the row of Foo model, which for I’ve called the association. For example, foo.nyaws where foo is single row.
In terms of SQL, this is something like SELECT * FROM foos LEFT JOIN nyaws ON foos.nyaw_id = nyaws.id AND foos.random_id = nyaws.something_else. So I basically want to be able to add that part after AND to each query done when someone calls the association.
There seems to be some suggestions around, but all official information mentions only hardcoded values, but nothing about using values from the model where the association is defined at.
Closest I’ve found is something like scope :with_company_id, lambda {|id| joins(:server).where('server.company_id = ?', id) }, but this would only work with a scope that would be used like a class normal method.