Reputation: 7
I have three models, car, service and appointment.
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
And Im using simple form to create an appointment to a car referencing a service
<%= 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 %>`
My appointment saves with the correct service, but the attributes of the service don´t
@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
I think the problem is with the params, but im not sure and I don´t know if im saving them correctly, service_attributes:[:request, :price, :provider].
Thanks in advance! (im using rails 5)
Upvotes: 0
Views: 67
Reputation: 20253
I think you may be going about this incorrectly. Since a Service has_many :appointments
and an Appointment has_many :services
(based on the comments), you have a m:m association and you might consider using has_many :through
. Something like:
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
Now, you should be able to do something with that bit of your params:
"service_id"=>["", "2", "3"]
To create appointment_services
(seems like you'll want to discard that ""
). You'll need to fiddle with it a bit and may be able to use accepts_nested_attributes_for :appointment_service
on Appointment
.
Upvotes: 1