rock_n_rolla
rock_n_rolla

Reputation: 357

Filtering a a collection in a options_from_collection_for_select

I am using the following select_tag in a form. Everything works perfectly and as expected.

<%= select_tag(:selling_shareholder_id, options_from_collection_for_select(@company.shareholders, 'id', 'name'), {prompt: 'Select Shareholder'})  %>

I would now like to only show shareholders in this list if the attribute number_of_stocks is not null or 0.

I tried the following line

<%= select_tag(:selling_shareholder_id, options_from_collection_for_select(@company.shareholders.where(number_of_stocks != 0), 'id', 'name'), {prompt: 'Select Shareholder'})  %>

and get the following error

undefined local variable or method `number_of_stocks' for #<#<Class:0x00007fb0c80ca9d8>:0x00007fb0c3d66688>

If I can successfully list out all the @company.shareholders in the select tag, shouldn't I easily be able to filter on one of their attributes?

Upvotes: 0

Views: 130

Answers (1)

Uelb
Uelb

Reputation: 4093

The only problem is your syntax:

Try this

<%= select_tag(:selling_shareholder_id, options_from_collection_for_select(@company.shareholders.where.not(number_of_stocks: 0), 'id', 'name'), {prompt: 'Select Shareholder'})  %>

I replaced

@company.shareholders.where(number_of_stocks != 0)

With

@company.shareholders.where.not(number_of_stocks: 0)

Upvotes: 2

Related Questions