-1

I have such model

class Ads::Posting < ActiveRecord:Base
  has_one :child, class_name: 'Ads::Posting', foreign_key: :posting_id
  belongs_to :parent, class_name: 'Ads::Posting', foreign_key: :posting_id
end

I need to write scope which gets all postings without child. Any ideas how to do that?

tereško
  • 58,060
  • 25
  • 98
  • 150
jizak
  • 382
  • 2
  • 13

2 Answers2

0

that model doesnt make sense!

a children is automatically a parent.

what exactly do you want to make? a tree?

then you need to add to migration

t.integer :parent_id, null: false

and in your model

has_one :child, class_name: 'Ads::Posting', foreign_key: :parent_id

for making it deeper, have a look at

https://github.com/stefankroes/ancestry

maybe thats helping you.

Tim Kretschmer
  • 2,272
  • 1
  • 22
  • 35
  • I'm using this for workflow of items. Due to the requirements when user creates posting it should be automatically available on the site (moderator still needs to look through it). When he updates some fields those changes shouldn't be available on the site before morerator approves those changes. Here I use 1-1 relation. And when moderator approves changes I just delete child item and overwrite changes to parent item. If you have better solution for that I'll be glad to hear. I'm not sure that my solution is the best. Thank you – jizak Jan 14 '13 at 19:53
0

I believe you can do this using a LEFT JOIN and a restriction on the where clause.

scope :my_scope, 
  joins("LEFT JOIN postings ON postings.ad_id = ads.id").where("postings.id IS NULL")
MurifoX
  • 14,991
  • 3
  • 36
  • 60