【发布时间】:2017-01-09 15:37:51
【问题描述】:
我在尝试提交嵌套 Rails 表单时收到“NoMethodError”。该表单用于创建预订,以及一个 serviceType - 预订(加入模型)。
我得到的错误是“# 的未定义方法‘属性’”
这是我的预订模型: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
这是预订控制器中的预订参数:
# 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 吗? (它通常在rails中进行......)。
任何帮助将不胜感激。谢谢!
【问题讨论】:
标签: ruby-on-rails forms nested-forms nested-attributes has-many-through