breadjesus
breadjesus

Reputation: 2059

How do I dynamically pick a table in Sequel associations?

I'm trying to create a one-to-one association between two models, called A and B. Model B can exist in either table Foo, if Foo exists, or table Bar, all other situations.

I tried using the :dataset flag of the one_to_one association method to get it to work, but can't seem to figure out how to make it work without introducing a circular dependency.

Is there a way to accomplish this with Sequel associations? Or is the best course of action to hand-write SQL?

Upvotes: 0

Views: 235

Answers (1)

Jeremy Evans
Jeremy Evans

Reputation: 12139

I'm not sure I completely understand what you are attempting to do, but from your description, you should just need to make B's table dependent on whether table Foo exists:

class B < Sequel::Model(DB.table_exists?(:Foo) ? :Foo : :Bar); end

If you really wanted to do it just for the association and not for all of model B, you can modify the FROM table in the association block:

A.many_to_one(:b){|ds| ds.from(ds.db.table_exists?(:Foo) ? :Foo : :Bar)}

I haven't tested either of these, but they should work. If that's not what you want, you probably want to add more detail to your description.

Upvotes: 1

Related Questions