-1

I'm getting "spans invalid" error when saving a job record that:

#job.rb
class Job < ApplicationRecord
    has_many :workspans
    has_many :spans, through: :workspans
end

I didn't get this error in rails 5.0, but on upgrading, I can't associate the spans.

The data is coming from a fairly standard rails form, with a checkbox for each span.

#new.html.erb
<%= Span.each do |span| %>
  <%= check_box_tag "job[span_ids][]", span.id %>
<% end %>

What has changed and how should I now set up the form to associate the spans with the @job ?

UPDATE, Detail

#jobs_controller
  def create
    @job = Job.new(job_params)    
    if @job.save
      flash[:success] = "Job Saved"
      redirect_to  action: :index
    else
      flash[:alert] = "Job Not Saved"
      render 'new'
    end
  end
Will
  • 4,498
  • 2
  • 38
  • 65
  • can you add some more information like controllers, models etc to the description? Also, please mention what is the exact error you are looking at? – Kartikey Tanna May 30 '18 at 16:28
  • That is the exact error – Will May 30 '18 at 16:34
  • @KartikeyTanna - more details added. – Will May 30 '18 at 16:38
  • 1
    Is it related to you? https://github.com/rails/rails/issues/23960 From Rails 5.2 `required: true` is the default. You need to mention `optional: true` – Kartikey Tanna May 30 '18 at 16:59
  • I wondered that @KartikeyTanna but I'm ok with the belongs_to's on the workspan model being required. Is it because there is no job_id because job hasn't been created maybe? – Will May 30 '18 at 17:07
  • ah, no. it's because in the Span model, there are some belongs_to associations that were not set and did not have , optional: true set. this meant the span was invalid, and Rails was noticing that, even though I wasn't really trying to save the span, just the relationship to it – Will May 30 '18 at 17:12
  • @KartikeyTanna - thanks for the steer. : ) – Will May 30 '18 at 17:12
  • you're welcome. Posted an answer out of comment so that other users can find it easily. – Kartikey Tanna May 30 '18 at 17:32
  • it's a horribly vague error message – Will May 30 '18 at 17:38
  • Yeah. But release notes would help while upgrading the versions. Need to go through each related point. – Kartikey Tanna May 30 '18 at 17:39

1 Answers1

1

From Rails 5.2 belongs_to is required by default. You need to mention optional: true to remove the error.

The related PR: https://github.com/rails/rails/pull/18937

The related issue on Rails repo: https://github.com/rails/rails/issues/23960

Kartikey Tanna
  • 1,423
  • 10
  • 24