2017-10-04 6 views
0

私はここに記載されているcollection_selectフィールドがあります。名前フィールドRails 5.1 collection_selectでnullをリストしない方法は?

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

は、特定の場合のために、その中にヌルを持っています。 nullでない場合は、collection_selectに名前をリストしたいだけです。

これを行う方法はありますか?

答えて

2

は、あなたのDocumentクラスにスコープを設定します。

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

その後、あなたはこのようにそれを使用することができます:

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

ありがとうございます。それは空の文字列だったので少し調整する必要がありました。これは私がその作品で終わったものです。スコープ:named_documents、 - > {where( "name <>" '").order(:name)} – spacerobot

+0

モデルにNOT NULL制約と検証を追加することでこれを修正する必要はありませんか? – max

+0

いいえ私はacts_as_treeとjstreeを使ってファイルマネージャのツリーを構築しています。カテゴリヘッダーでない場合、フィールドは空の場合もあります。 – spacerobot

0

あなたは私がそれを更新

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

を行うことができます。

+0

感謝。私は未定義のメソッド "拒否"エラーを取得しています。 – spacerobot

+0

コレクションを実際に反復するように更新しました。 –

関連する問題