Mel
Mel

Reputation: 2685

How do I write a scope in Rails?

I am trying to learn how to write scopes in Rails.

I have models for user, organisation and organisation request. The associations are:

User
  has_one :organisation 

Organisation
  belongs_to :owner, class_name: 'User'
  has_many :organisation_requests

Organisation_request
  belongs_to :organisation

In my organisation request model, I'm trying to write a scope to pick out all the organisation requests that belong to the organisation's owner.

scope :same_org, where(:organisation_id => owner.organisation_id)

Then in my organisation_requests controller, I have:

def index
    @organisation_requests = OrganisationRequest.same_org
end

I tried the above. Owner is an alias for user. In each organisation, one user is nominated as that organisation's owner. I want that user to see an index of the organisation requests that come in for that owner's organisation.

Can anyone see what I've done wrong here? I'm not understanding something about how to write scopes.

Upvotes: 1

Views: 98

Answers (2)

Andrey Deineko
Andrey Deineko

Reputation: 52357

The upvoted answer is wrong (nothing personal, @Hasmukh Rathod) - there is no organisation_id column in users table (it's actually vice versa - there is a user_id column in organisations table).

I would suggest the following solution:

scope :same_org, ->(owner_id) { joins(organisation: :user).where(users: { id: owner_id }) }

Having the above scope, what you'll need to do, is to pass the owner_id as an argument. I'm sure there is a way to get it working without passing an argument to scope, but I'm not yet sure how (I've just woke up :D).

So example:

owner_id = User.find(1).id
OrganisationRequest.same_org(owner_id) # would give you the expected collection of requests

Upvotes: 1

Hasmukh Rathod
Hasmukh Rathod

Reputation: 1118

In your model, try this:

scope :same_org, -> {where(:organisation_id => owner.organisation_id) }

Upvotes: 2

Related Questions