1

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
Bevilacqua
  • 465
  • 3
  • 8
  • 19
  • 1
    please add your model to the question – neydroid Jul 22 '16 at 21:38
  • 1
    Are you using rails 5 ?, I kind of remember reading that belongs_to associations are required in rails 5, unless you specify required: false, or something like that, I don't remember. – fanta Jul 22 '16 at 21:44
  • I am using rails 5 – Bevilacqua Jul 22 '16 at 21:44
  • Just looked it up you're right! Thank you!! – Bevilacqua Jul 22 '16 at 21:45
  • 2
    ok, so, the fix is to specify belongs_to :area, optional: true, that's in case you want to have that kind of data. It was added to prevent data inconsistencies. – fanta Jul 22 '16 at 21:46
  • 1
    In Rails 5 `belongs_to` associations require the associated object to be present. See the [discussion about this new feature](https://github.com/rails/rails/issues/18233). – spickermann Jul 22 '16 at 22:04
  • @fanta Write up the answer so you can get interwebz points and someone else down the road can find an answer. – MarsAtomic Jul 22 '16 at 22:37

2 Answers2

3

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
fanta
  • 1,489
  • 13
  • 15
1

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

Paulo Abreu
  • 1,716
  • 11
  • 16