belongs_to has conditions that allow you to filter the query of the associated table, but would it be too much of an edge case to provide something like a conditions for the table of the model that the belongs_to is defined on?
This would allow easier belongs_to for columns that are foreign keys to multiple tables where the associated table is defined by other columns in the child, e.g.
class Pig < ActiveRecord::Base
belongs_to :pig_friend, foreign_key: :friend_id, class_name: Pig
belongs_to :frog_friend, foreign_key: :friend_id, class_name: Frog
belongs_to :boyfriend, foreign_key: :friend_id, class_name: Frog, child_conditions: [“name = ‘Miss Piggy’”], conditions: [“name = ‘Kermit’”]
(The workaround is to just have a method to do it rather than an association, but I think you could get a lot more out of it as an association, although that also means it would require more changes to get it to work.)
It could also be used to filter known invalid ids in a legacy schema that cannot be changed easily without significant external changes:
class User < ActiveRecord::Base
belongs_to :address, child_conditions: [“address_id != ?”, MyApplication.INVALID_ADDRESS_ID]
BTW- a messy workaround for that specific use case is: https://github.com/garysweaver/activerecord-define_nils
(and I’m totally aware that storing invalid values in foreign keys is a bad idea- fixing that will require a lot more work at the moment than the workaround, and it seemed like it would be a nice tool.)
Odds are this is a bad idea and there is a better way to do all of this or a reason that something like child_conditions is not provided in AR.
Thanks in advance for any advice or assistance.