spacerobot
spacerobot

Reputation: 297

Rails 5.1 how to not list nulls in a collection_select?

I have a collection_select field listed here:

    <%= form.collection_select :parent_id, Document.order(:name), :id, :name,
    {:include_blank => ''}, {:class => 'form-control'} %>

The name field has nulls in it for certain cases. I only want to list the name in the collection_select if it is not null.

Is there a way to do this?

Upvotes: 0

Views: 60

Answers (2)

ruby_newbie
ruby_newbie

Reputation: 3275

you can do

<%= form.collection_select :parent_id, Document.named_documents.reject{|d| d.name.nil?}.order(:name), :id, :name,
    {:include_blank => ''}, {:class => 'form-control'} %>

I updated it.

Upvotes: 0

EJAg
EJAg

Reputation: 3298

Set up a scope in your Document class:

##document.rb
scope :named_documents, -> { where.not(name: nil).order(:name) }

Then you can use it like this:

 <%= form.collection_select :parent_id, Document.named_documents, :id, :name, {:include_blank => ''}, {:class => 'form-control'} %>

Upvotes: 2

Related Questions