0

I have a table called Materials and I have created a search form. In the form I want to have select boxes containing the names of the search options. So for example, if you want to search by subject, I want a dropdown with one of each of the subjects. I have code for this that works:

@subject = Material.unscoped.select(:subject).where("materials.subject IS NOT NULL
and materials.subject != '' ").uniq

This gives me what I want with the following form helper:

<%= select_tag "subject", options_from_collection_for_select(@subject, "subject", 
"subject"), :include_blank => true, :class => "input_field" %>

BUT - I now want to select only those subjects from Materials that are shared. So I selected the shared Materials using:

@shared = Material.where(:status => 'shared')

And then ran this code:

@subject = @shared.unscoped.select(:subject).where("@shared.subject IS NOT NULL
and @shared.subject != '' ").uniq

Which doesn't work. I assume it's because the sql code can't understand the @shared object. But how to do this?

Note:

I tried using:

@subject = @shared.uniq.pluck(:subject).reject! { |s| s.empty? }

This gives an array of the right fields but then that doesn't work with options_from_collection_for_select.

0

2 Answers 2

1

You can create a scope for the shared query like this:

scope :shared, where(:status => 'shared')

And then you can chain ActiveRecord methods to your liking:

@subject = Material.select(:subject).where("materials.subject IS NOT NULL 
  AND materials.subject != '' ").shared.uniq

More on scopes here: http://guides.rubyonrails.org/active_record_querying.html#scopes

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. This works too and the scoping is useful for other things as well.
1

Try this

@subject = Material.unscoped.select(:subject).where("subject IS NOT NULL and materials.subject != '' and status = 'shared'").uniq 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.