如何在Rails中将每个值从数组保存到数据库?

问题描述

我想存储数组中的每个值。
例如,表格向我发送了以下数据:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
我希望数据库将数据存储为:

"attendance"=>{"event_id"=>"6","member_id"=>["16","28","26"]}

我尝试使用在Rails中插入数据的常规方法,但是失败了,因为未通过INSERT INTO "attendances" ("event_id","member_id") VALUES ("6","16") INSERT INTO "attendances" ("event_id","28") INSERT INTO "attendances" ("event_id","26") (我尝试在member_id之后打印member_id Attendance.new(attendance_params)

def create
    @attendance = Attendance.new(attendance_params)
    # puts @attendance[:event_id]
    # puts @attendance[:member_id] -> Nothing showed up here.

    if @attendance.save
      flash[:success] = "Successfully created"
      redirect_to new_attendance_path
    else
      @error_msg = @attendance.errors.full_messages
      flash[:error] = @error_msg # Prints ["Member must exist"]
      redirect_to new_attendance_path
    end
  end

我还尝试在模型中创建一个新函数来更改Attendance.new,但它将返回
NoMethodError - undefined method `new_each' for #<Class:0x000000000d1e7280>: app/controllers/attendances_controller.rb:17:in `create'
这是我目前的模型:

class Attendance < ApplicationRecord
  belongs_to :event
  belongs_to :member
  
  # def new_each(attendance)
  #   attendance_event = attenance[:event_id]
  #   attendance_members = attendance[:member_id]

  #   I tried to iterate and save each data here.
  # end
end

那么,如何保存来自数组输入(来自表单)的每个值并将其保存到数据库?
任何答案和评论将不胜感激。

解决方法

您正试图批量增加出勤,为此您可以做两件事,

  1. 使用gem bulk_insert,这很容易使用,这里是链接https://github.com/jamis/bulk_insert
  2. 您需要遍历params中的所有成员和事件,并为它们创建一个记录。尽管这是一种非常肮脏的方式。

示例代码将是这样。您可以根据需要进行修改。

   errors = {}
   attendance_params[:member_id].each do |member_id|
       attendence = Attendence.new(event_id:attendance_params[:event_id],member_id: member_id)
       errors[member_id] = "Could not save attendance,error = 
                             attendance.errors.full_messages" unless 
                             attendence.save
   end

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...