belongs_to with filtering on values in the current model's foreign_key

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’”] end

(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] end

BTW- a messy workaround for that specific use case is: GitHub - garysweaver/activerecord-define_nils: Allows you to redefine what is translated to nil on read and what is stored instead of nil for specified attributes.

(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.

Sorry the subject/topic subject makes absolutely no sense. Should have said “belongs_to child_conditions” or “filtering belongs_to with conditions for child table in query”.