[英]Rails - accepts_nested_attributes_for and presence validation
[英]Rails accepts_nested_attributes_for validation error
模型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
型號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看起來像:
#<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引起的嗎? 如何解決問題? 提前致謝。
嘗試將inverse_of屬性添加到關聯中。
請記住,默認情況下,rails 5會要求屬下關聯。
http://blog.bigbinary.com/2016/02/15/rails-5-makes-belong-to-association-required-by-default.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.