型号ride.rbRails的accepts_nested_attributes_for验证错误
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
型号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
我有保存对象搭在操作创建一个问题。有错误:
ActiveRecord::RecordInvalid: Validation failed: Start address ride must exist,
目的地地址必须存在。当我在ride.save之前放置断点时,骑行看起来像:
#<Ride id: nil, price: 12.0, distance: 5.8, created_at: nil, updated_at: nil, user_id: 1, provider_id: 1>
错误的原因是什么?为什么需要start_address和destination_address?它是由关联has_one引起的吗?如何解决问题? 在此先感谢。
你使用的是什么版本的导轨? – neydroid
@neydroid rails 5.0.0 –