1

當我得到一個‘試圖提出一個嵌套的軌道形式時NoMethodError’。該表單用於創建預留,以及serviceType - 預留(連接模型)。導軌的has_many通過加盟模式未定義ID:「未定義的方法'屬性爲#」提交嵌套形式

我得到的錯誤是「未定義的方法'屬性爲#」

這是我的預訂模式:reservation.rb

module Booking 
class Reservation < ActiveRecord::Base 
    has_many :service_type_reservations, inverse_of: :reservation, dependent: :destroy 
    accepts_nested_attributes_for :service_type_reservations, allow_destroy: true 

    has_many :service_types, through: :service_type_reservations, dependent: :destroy 
    has_one :customer_reservation, dependent: :destroy 
    has_one :customer, through: :customer_reservation, dependent: :destroy 

    validates_uniqueness_of :service_type_reservations 
end 
end 

這是服務類型的預定模式:servicetypereservation.rb

module Booking 
class ServiceTypeReservation < ActiveRecord::Base 
    belongs_to :service_type 
    belongs_to :reservation 
    belongs_to :service_calendar 

    validates :reservation, presence: true 
    validates :service_type, presence: true 
end 
end 

在我的預訂控制器,這些都是新的,創建函數:reservations_controller.rb

# GET /reservations/new 
def new 
    @serviceTypes = ServiceType.all 
    @reservation = Reservation.new 
    @reservation.build_service_type_reservations 
    @numberOfServices = @serviceTypes.length 
    if params[:service_type_id] 
    @selectedService = ServiceType.find(params[:service_type_id]) 
    end 
end 

# POST /reservations 
def create 
    @serviceTypes = ServiceType.all 
    @reservation = Reservation.new(reservation_params) 

    if @reservation.save 
    redirect_to new_customer_path(reservation_id: @reservation.id), notice: 'Reservation was successfully created.' 
    else 
    render :new 
    end 
end 

這是保留控制器保留PARAMS:

# Only allow a trusted parameter "white list" through. 
    def reservation_params 
    respond_to do |format| 
     format.html { params.require(:reservation).permit(:updated_at, :created_at, :total_price, :customer_id, service_type_reservations_attributes: [:occupancy, :check_in, :check_out, :date, :service_type_id])} 
    end 
    end 

要創建嵌套的表格:

<%= form_for(@reservation) do |f| %> 
    <%= f.fields_for :service_type_reservations do |service_reservation_form| %> 

我敢肯定它是創造了新的服務類型保留,但它有一個未定義的ID。我不確定id是否屬於該屬性。我試着改變一下代碼,並得到錯誤「未定義的屬性'0'」,所以我很確定這是id。

當我創建預留(和servicetype-reservation)時,它不會自動生成一個id嗎? (它通常在軌道中..)。

任何幫助,將不勝感激。謝謝!

回答

0

我刪除行

validates_uniqueness_of :service_type_reservations 

從reservations.rb

形式現在可以提交。之前沒有這一行發生錯誤,但它突然開始工作。我想我只需要重新啓動服務器。