jdkealy
jdkealy

Reputation: 4907

How do I create a Sequel ORM self referential relationship?

If I had two tables, users and blocked_users, how would I define the relationship from blocked_users to users?

For example,

class User < Sequel::Model

  one_to_many :blocked_users,     :key=>:source_id
  one_to_many :blocked_by_users,  :key=>:target_id, :class => BlockedUser

end

What would I put in here?:

# table => blocked_users, fields => "source_id", "target_id"

Class BlockedUser < Sequel:Model

  #fail => belongs_to :blocking_user_account, :class => User, :primary_key => :source_id
  #fail => belongs_to :blocked_user_account,  :class => User, :primary_key => :target_id

end

How would I refer to the User model from the BlockedUser model?

I tried the fix below and am confused on the following error; With the BlockedUser class restructured like so:

class BlockedUser < Sequel::Model
  many_to_one :blocking_user, :class=>:User, :primary_key => :source_id
  many_to_one :blocked_user,  :class=>:User, :primary_key => :target_id
end

I get the following error:

.9.3p0 :003 > BlockedUser.all.first.blocked_user
   INFO - (0.000427s) SELECT * FROM `blocked_users`
NoMethodError: undefined method `blocked_user_id' for #<BlockedUser @values={:id=>1, :source_id=>1, :target_id=>2}>

This does execute the appropriate query, however:

class BlockedUser < Sequel::Model
  many_to_one :source, :class=>:User
  many_to_one :target, :class=>:User
end

BlockedUser.all.first.source

Upvotes: 1

Views: 589

Answers (1)

Jeremy Evans
Jeremy Evans

Reputation: 12139

You should specify the class name as a symbol (and use many_to_one instead of belongs_to):

class BlockedUser < Sequel:Model
  many_to_one :blocking_user, :class=>:User, :primary_key => :source_id
  many_to_one :blocked_user,  :class=>:User, :primary_key => :target_id
end

Upvotes: 2

Related Questions