0

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.

2
  • what version of rails are you using? Commented Jul 21, 2016 at 18:04
  • @neydroid rails 5.0.0 Commented Jul 21, 2016 at 18:31

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@Mabama, thank you for your help, when I added require: false for belongs_to, create method works good.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.