我有三种模式,汽车,服务和约会。
class Car < ApplicationRecord
belongs_to :user
has_many :appointments, dependent: :destroy
end
class Service < ApplicationRecord
has_many :appointments
end
class Appointment < ApplicationRecord
belongs_to :car
belongs_to :service
accepts_nested_attributes_for :service
end
我用简单的表格创建了引用服务的汽车的约会
<%= simple_form_for [@car, @appointment] do |a| %>
<%= a.input :date %>
<%= a.input :description, label: "descripción" %>
<%= a.input :location, label: "ubicación" %>
<%= a.association :service, as: :check_boxes, include_blank: false %>
<%= a.button :submit %>
<% end %>`
我的约会保存了正确的服务,但该服务的属性不正确
@car = Car.find(params[:car_id])
@appointment = Appointment.new(appointment_params)
@service = Service.new(params[ :service])
@appointment.service = @service
@appointment.car = @car
def appointment_params
params.require(:appointment).permit(:date, :description, :location, :status, :requests, service_attributes:[:request, :price, :provider])
end
我认为问题出在参数上,但是我不确定,我不知道我是否正确保存了参数,service_attributes:[:request,:price,:provider]。
提前谢谢! (即使用滑轨5)
答案 0 :(得分:1)
我认为您可能会对此进行错误处理。由于Service has_many :appointments
和Appointment has_many :services
(基于注释),因此您具有m:m关联,可以考虑使用has_many :through
。像这样:
class Car < ApplicationRecord
belongs_to :user
has_many :appointments, dependent: :destroy
end
class AppointmentService < ApplicationRecord
belongs_to :service
belongs_to :appointment
end
class Service < ApplicationRecord
has_many :appointment_services
has_many :appointments, through: :appointment_services
end
class Appointment < ApplicationRecord
belongs_to :car
has_many :appointment_services
has_many :services, through: :appointment_services
end
现在,您应该可以使用那部分参数进行操作了:
"service_id"=>["", "2", "3"]
要创建appointment_services
(似乎您想丢弃该""
)。您需要稍微摆弄一下,并且可以在accepts_nested_attributes_for :appointment_service
上使用Appointment
。