2

I want to return Users with Books which are part of a scope -

class User < ActiveRecord::Base
  has_many :books
end

class Book < ActiveRecord::Base
  belongs_to :user

  scope :published, -> { where (status: 'Published') }
end

So

Book.published

returns all the published books. I'm trying to define a scope of all users who have one or more published books.

Knowing that

User.joins(:books).uniq.all

returns all users with a book (from Rails: How to get objects with at least one child?) - can I add a scope to that, or is there a better approach?

Community
  • 1
  • 1
dan
  • 1,030
  • 1
  • 9
  • 24

1 Answers1

2

Firstly, the class name for the model should be singular and If I understood correctly, you want all users with a book within the scope published then I would place that scope in User model with a slight change like below

class User < ActiveRecord::Base
  has_many :books
  scope :published, -> { joins(:books).where(books: { status: 'Published' }) }
end

Now you can do User.published which returns all users with a book whose status is Published

dan
  • 1,030
  • 1
  • 9
  • 24
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • I'm just working through it now - I currently get the error message - ActiveRecord::StatementInvalid: PG::UndefinedTable: ERROR: missing FROM-clause entry for table "child" - googling this got the following rails issue on github - https://github.com/rails/rails/issues/13531#issuecomment-35103068 - 'm trying to work out if its the same thing - what do you think? – dan Sep 23 '15 at 07:25
  • @RADan Is your table named `child`? or `children`? – Pavan Sep 23 '15 at 07:26
  • can i just check - that -> { joins(children) ... is that the plural or singular of the class name? – dan Sep 23 '15 at 07:28
  • I was trying to make the class names generic, but I don;t think i made a good choice :) – dan Sep 23 '15 at 07:29
  • @RADan Try putting `self.table_name = "child"` in `Child` model and see. – Pavan Sep 23 '15 at 07:31
  • I think rather than tying to make it generic I should just use actual table names, as is less confusing - will update question :) – dan Sep 23 '15 at 07:34
  • @RADan Yeah! table names should be plural. In your case **child** should be **children** – Pavan Sep 23 '15 at 07:35