模型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
模型地址.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引起的吗?如何解决问题? 提前谢谢。
答案 0 :(得分:1)
尝试将inverse_of属性添加到关联。
请记住,rails 5默认情况下需要进行belongs_to关联。
http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html