Rails 替换集合而不是从 has_many 嵌套属性表单添加到它 [英] Rails replace collection instead of adding to it from a has_many nested attributes form

查看:29
本文介绍了Rails 替换集合而不是从 has_many 嵌套属性表单添加到它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have these models (simplified for readability):

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 呈现,用户可以在其中添加新的开放时间.在提交这些开放时间时,我想总是替换旧的(如果存在).目前,如果我通过参数(例如)发送值:

I have a somewhat dynamic form which is rendered through javascript where the user can add new opening hours. When submitting these opening hours I would like to always replace the old ones (if they exist). Currently if I send the values via params (e.g.):

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 总是替换营业时间,或者我每次都必须手动清空控制器中的集合?

These new business hours get added to the existing ones. Is there a way to tell rails to always replace the business hours or do I manually have to empty the collection in the controller every time?

推荐答案

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

Bit optimizing the solution proposed @robertokl, to reduce the number of database queries:

def business_hours_attributes=(*args)
  self.business_hours.clear
  super(*args)
end

这篇关于Rails 替换集合而不是从 has_many 嵌套属性表单添加到它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆