【问题标题】:simple_form association not saving with attributessimple_form 关联不与属性一起保存
【发布时间】:2019-01-03 17:02:58
【问题描述】:

我有三种型号,汽车、服务和预约。

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]。

提前致谢! (我使用 Rails 5)

【问题讨论】:

    标签: ruby-on-rails database parameters associations simple-form


    【解决方案1】:

    我认为您可能会错误地处理此问题。由于 Service has_many :appointmentsAppointment has_many :services(基于 cmets),您有一个 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(好像你想放弃那个"")。你需要稍微摆弄一下,也许可以在Appointment 上使用accepts_nested_attributes_for :appointment_service

    【讨论】:

    • jvillian 是的,我确定,因为Service 是一个预约可以选择的服务“菜单”,有固定的价格、供应商等。我不确定这是否是最好的方式虽然...
    • 嗯。好的,我明白了。您能否将表单提交产生的​​params 添加到您的问题中?我有一种感觉accepts_nested_attributes_for 在这里可能不合适。
    • 当然,"约会"=>{"date(1i)"=>"2018", "date(2i)"=>"7", "date(3i)"=>"26 ", "date(4i)"=>"15", "date(5i)"=>"21", "description"=>"prubeasny", "location"=>"", "service_id"=>[" ", "2", "3"]}, "commit"=>"创建约会", "控制器"=>"约会", "action"=>"create", "car_id"=>"8"}
    • 困扰我的是 "service_id"=>["", "2", "3"] 只保存第一个,而不保存它的属性(价格、供应商、等)
    • 您的Services 似乎应该在创建Appointment 之前的某个时间创建(以便在创建appointment 时可以从services 的菜单中进行选择)。对吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-15
    • 1970-01-01
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多