On Sunday, December 3, 2017 at 7:51:15 PM UTC-8, tdrive wrote:
>
> I'm trying to rewrite my project from AR to Sequel and I have a problem.
>
> For examle we have tables
>     create_table :users do |t|
>       t.string :name
>     end
>
>     create_table :relations do |t|
>       t.string :type
>       t.integer :user_id
>       t.integer :with_user_id
>     end
>
> and models
> class Relation::Base < ActiveRecord::Base
>   self.table_name = :relations
>
>   belongs_to :user
>   belongs_to :with_user, class_name: "User"
> end
>
> class Relation::Colleague < Relation::Base
> end
>
> class Relation::Friend < Relation::Base
> end
>
> class User < ActiveRecord::Base
>   has_many :friend_relations, class_name: "Relation::Friend"
>   has_many :colleague_relations, class_name: "Relation::Colleague"
>
>   has_many :friends, through: :friend_relations, source: :with_user, 
> class_name: "User"
>   has_many :colleagues, through: :colleague_relations, source: :with_user, 
> class_name: "User"
> end
>
>
> How should I rewrite the :friends and :colleagues  associations without 
> hardcoded conditions type='Relation::Colleague' and type='Relation::Friend
> '
>

Sequel doesn't ship with support for polymorphic associations, so if you 
want it in Sequel you have to hardcode the conditions, with something like:

class User
  many_to_many :friends, join_table: :relations, right_key: :with_user_id, 
class: self do |ds|
    ds.where{relations[:type] =~ 'Relation::Friend'}
  end
end

These types of associations are fairly easy to metaprogram by using a loop 
to handle all your polymorphic types.

There is the sequel_polymorphic external plugin that you could try, 
especially if you want easier access to modify such polymorphic 
associations. Alternatively, split your polymorphic join table into 
separate tables for friends and colleagues and then you don't need any 
polymorphism and can benefit from the increased simplicity and the ability 
to enforce referential integrity in the database.

Thanks,
Jeremy

-- 
You received this message because you are subscribed to the Google Groups 
"sequel-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To post to this group, send email to [email protected].
Visit this group at https://groups.google.com/group/sequel-talk.
For more options, visit https://groups.google.com/d/optout.

Reply via email to