Rails中点击按钮批量创建对象:template_sections转Section实现
Rails 模板转普通区块(Deploy Template)功能实现需求
我有 template_sections 和 sections 两类模型,希望通过视图按钮触发模板部署逻辑,当前可选两种实现路径:
- 路径a:查询指定 template_id 下的全部 template_sections 数据,将查询结果从视图传递给 sections_controller
- 路径b:直接在 sections_controller 的 transform 方法内部查询获取对应模板下的 template_sections 集合
后续通用流程要求:遍历查询得到的模板区块集合,为每条记录创建新的 section 实例,将新实例的 is_template 设为 0、template_id 设为 nil 后完成持久化保存。
现有代码片段
视图层代码(View)
<div class="col-2 deploy-template"> <%= button_to 'Deploy Template', transform_sections_path, method: :post, *{需要补充此处的参数传递或控制器调用逻辑}*, remote: true, type: 'button', class: "btn btn-secondary btn-sm ml-0 mr-4" %> </div>
控制器层代码(Controller)
def new @section = Section.new if params[:is_template] date = (Time.at(params['day'].to_i*86400-1)).strftime("%Y-%m-%d") @section.starts_at_datetime = (date + ' ' + params['time']).in_time_zone rescue nil else @section.starts_at_datetime = (params['date'] + ' ' + params['time']).in_time_zone rescue nil end respond_to do |format| format.js end end def create @section = Section.new(section_params) @section.account_id = session_account_id @section.is_template = true if params[:section][:is_template] == 'true' @section.template_id = params[:section][:template_id] respond_to do |format| if @section.save format.js flash.now[:success] = "saved successfuly" create_event @section, "create", "Create" else flash.now[:danger] = "#{@section.errors.full_messages}" format.js { render 'layouts/notifications' } end end end def transform template_sections.each do |template_section| # 遍历每个模板区块,设置is_template=0、template_id=nil后保存为普通section end end
核心诉求
求符合Rails开发规范的完整可行实现方案。
内容的提问来源于stack exchange,提问作者AccNeeder
相关产品推荐
相关产品推荐

