Ask A Question

Notifications

You’re not receiving notifications from this thread.

How do I return a scope that I think includes a select?

Clint Baker asked in Rails

Hello,

I have a Model called Orgchart and it contains a position. In the users table there is an orgchart_id for each user. I have a select box on a form and I want to fill it with all the positions from orgcharts table that are NOT connected to a user in the users table. So essentally I feel like this should be a nil result from a nested select somehow but I'm drawing a blank. Probably the scope could be called available_positions as that would make more sense. Essentally return all of the Orgchart records where position is unused.

scope :empty_positions, -> {  Not sure how to construct this! }

How do I do this?

Clint

Reply

I just tried to do the same with my Users and Roles

In my Role model I defined a class method call available

def self.available
@users = User.all
Role.where.not(id: @users.pluck(:role_id).uniq)
end

In my form for the dropdown I use this

<%= f.collection_select :role_id, Role.available, :id, :name, {class: 'form-control bootstrap-select', required: :required} %>

I think you could adjust the code above to work with your orgchart / positions

Reply

Thanks Amie! That worked!! So great to be able to get help to figure out some of the problems that crop up and where you have a mental block. So much saner than toiling with it for hours!

Clint

Reply

Oh that's great to hear, Clint - happy it was a help :)

Reply
Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 76,990+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    Screencast tutorials to help you learn Ruby on Rails, Javascript, Hotwire, Turbo, Stimulus.js, PostgreSQL, MySQL, Ubuntu, and more. Icons by Icons8

    © 2023 GoRails, LLC. All rights reserved.