0

I have a Rails 3 application that contains a table called worequests.

worequest.rb model contains:

  belongs_to :statuscode

Statuscodes has a boolean field called closed.

I want to be able to get a list of all worequests where worequest.statuscode.closed == true.

For example:

def index2
  @search = Worequest.closed.search(params[:q])
  @worequests = @search.result
end

OR

worequests.notclosed.count

I tried these in the worequest model:

scope :closed, joins(:statuscode).where(:statuscode.closed => true)
scope :closed, joins(:statuscode).& Statuscode.closed
scope :closed, joins(:statuscode) & Statuscode.closed

def self.closed
  joins(:statuscode) & Statuscode.closed
end

def self.notclosed
  joins(:statuscode) & Statuscode.notclosed
end

Thanks for the help!

Reddirt
  • 5,913
  • 9
  • 48
  • 126
  • Your question is confusing, you say that you have "a Rails 3 table", do you mean that you have a table in a Rails 3 application? The answers are very different depending on if you're using Rails 3 or 4. – smathy Feb 19 '15 at 16:25

2 Answers2

0

Since Rails 4, named scopes must be given a callable, such as a lambda:

scope :closed, -> { joins(:statuscode).where(statuscodes: { closed: true }) }

should do the trick (note the singular :statuscode in the join and the plural statuscodes table name in the where condition).

janfoeh
  • 10,243
  • 2
  • 31
  • 56
0

I'm not sure I understand the question correctly. Do you just want a scope on your class so you get all closed ones?

class StatusCode < ActiveRecord:Base
  belongs_to :worequest
end

class Worequest < ActiveRecord:Base
  has_one :status_code do
    def closed
      where(closed: true)
    end
  end
end

closed_quests: Worequest.all.closed

I've based my answer on the question asked here: How do you scope ActiveRecord associations in Rails 3?

As this is how I interpreted your question. For rails 4, I recommend using the other answer.

Community
  • 1
  • 1
codingbunny
  • 3,989
  • 6
  • 29
  • 54
  • Currently Worequest belongs_to :statuscode not the other way round. Is there a way to do this without changing that? – Reddirt Feb 19 '15 at 16:17
  • you should be able to do the same what I did with the reverse associations. Both take a block, so you can still do the same trick i did. – codingbunny Feb 20 '15 at 07:24