简体   繁体   中英

ROR: Collection select with with include_blank won't allow nil

I have a collection select in my form:

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

And my model validation has no requirement for an area.

It was my understanding that by using include_blank would allow me to choose nil. However i get a validation error "Area must exist"

EDIT:

Here is the important code in the model:

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

Rails 5 forces you to set all belongs_to associations unless you specify optional: true . It was added to prevent data inconsistencies, so, in case you want it to behave like previous rails versions, you just have to change your association to this:

belongs_to :area, optional: true

In Rails 5 validate is set to true by default. Please check for :optional and :required options on belongs_to documentation for more details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM