1

私は自分のフォームでコレクションを選択しています:

<div class="field">
    <%= f.label :area %>
    <%= f.collection_select(:area_id, Area.all, :id, :name, include_blank: "No area.") %>

また、私のモデルの検証には、領域の要件はありません。

include_blank を使用すると、nil を選択できるようになるというのが私の理解でした。ただし、「領域が存在する必要があります」という検証エラーが表示されます

編集:

モデルの重要なコードは次のとおりです。

has_many :ratings, dependent: :destroy
has_many :noise_ratings, dependent: :destroy
has_many :statuses, dependent: :destroy
has_many :checkins, dependent: :destroy

has_and_belongs_to_many :features

belongs_to :area
belongs_to :campus

validates :name, presence: true, uniqueness: { scope: :campus_id, message: "unique space for each campus." }
validates :description, presence: true
validates :campus_id, presence: true
4

2 に答える 2

3

Rails 5では、 optional: trueを指定しない限り、すべての属している関連付け設定する必要があります。これはデータの不整合を防ぐために追加されたものであるため、以前の Rails バージョンのように動作させたい場合は、関連付けを次のように変更するだけです。

belongs_to :area, optional: true
于 2016-07-22T22:47:11.383 に答える
1

Rails 5 では、validate はデフォルトで true に設定されています。詳細については、 belongs_toドキュメントの :optional および :required オプションを確認してください。

于 2016-07-22T22:40:44.197 に答える