All threads / How do I return a scope that I think includes a select?

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

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

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

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

Join the discussion

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

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

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

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.