Rails 替换集合,而不是从 has_many 嵌套属性表单添加到集合中

2024-04-13

我有这些模型(为了便于阅读而简化):

class Place < ActiveRecord::Base
  has_many :business_hours, dependent: :destroy

  accepts_nested_attributes_for :business_hours
end

class BusinessHour < ActiveRecord::Base
  belongs_to :place
end

还有这个控制器:

class Admin::PlacesController < Admin::BaseController
  def update
    @place = Place.find(params[:id])

    if @place.update_attributes(place_params)
      # Redirect to OK page
    else
      # Show errors
    end
  end

  private

  def place_params
    params.require(:place)
      .permit(
        business_hours_attributes: [:day_of_week, :opening_time, :closing_time]
      )
  end
end

我有一个通过 javascript 呈现的动态表单,用户可以在其中添加新的开放时间。在提交这些开放时间时,我希望始终替换旧的开放时间(如果存在)。目前,如果我通过参数发送值(例如):

place[business_hours][0][day_of_week]: 1
place[business_hours][0][opening_time]: 10:00 am
place[business_hours][0][closing_time]: 5:00 pm
place[business_hours][1][day_of_week]: 2
place[business_hours][1][opening_time]: 10:00 am
place[business_hours][1][closing_time]: 5:00 pm

...等等

这些新的营业时间将添加到现有的营业时间中。有没有办法告诉 Rails 始终更换营业时间,或者我每次都必须手动清空控制器中的集合?


位优化@robertokl提出的解决方案,以减少数据库查询的数量:

def business_hours_attributes=(*args)
  self.business_hours.clear
  super(*args)
end
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails 替换集合,而不是从 has_many 嵌套属性表单添加到集合中 的相关文章

随机推荐