Prezes Łukasz
Prezes Łukasz

Reputation: 968

Rails accepts_nested_attributes_for validation error

Model ride.rb

class Ride < ActiveRecord::Base
..
has_one :start_address, class_name: "Address"
has_one :destination_address, class_name: "Address"

accepts_nested_attributes_for :start_address, :destination_address
..
end

Model address.rb

class Address < ActiveRecord::Base
  belongs_to :ride
end

rides_controller.rb

class RidesController < ApplicationController
  before_action :authenticate_user!
  before_action :set_providers, only: [:new, :create]
  expose :rides
  expose :ride, attributes: :ride_params
  def index
  end

  def new
    @start_address = ride.build_start_address
    @destination_address = ride.build_destination_address
  end

  def create
    ride.user = current_user
    if ride.save
      redirect_to root_path, notice: I18n.t('shared.created', resource: 'Ride')
    else
      render :new
    end
  end

  private
  def ride_params
    params.require(:ride).permit(:price, :provider_id,
        start_address_attributes: [:street, :city, :country],
        destination_address_attributes: [:street, :city, :country])
  end

  def set_providers
    @providers = Provider.all
  end
end

I have a problem with saving object ride in create action. There is error:

ActiveRecord::RecordInvalid: Validation failed: Start address ride must exist, 

Destination address ride must exist. When I put breakpoint before ride.save, ride looks like:

#<Ride id: nil, price: 12.0, distance: 5.8, created_at: nil, updated_at: nil, user_id: 1, provider_id: 1>

What is cause of the error? Why start_address and destination_address are required? Is it caused by association has_one? How to resolve a problem? Thanks in advance.

Upvotes: 0

Views: 1276

Answers (1)

Mabana
Mabana

Reputation: 36

Try to add inverse_of attribute to associations.

Remember that rails 5 makes belongs_to association required by default.

http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html

Upvotes: 2

Related Questions