【问题标题】:How to save each value from an array to database in Rails?如何将数组中的每个值保存到 Rails 中的数据库中?
【发布时间】:2020-09-08 07:02:56
【问题描述】:

我想存储数组中的每个值。
例如表单向我发送以下数据:
"attendance"=>{"event_id"=>"6", "member_id"=>["16", "28", "26"]}
我希望数据库将数据存储为:

INSERT INTO "attendances" ("event_id", "member_id") VALUES ("6", "16")
INSERT INTO "attendances" ("event_id", "member_id") VALUES ("6", "28")
INSERT INTO "attendances" ("event_id", "member_id") VALUES ("6", "26")

我尝试使用通常的方式在 Rails 中插入数据,但它失败了,因为 member_ids 没有通过(我尝试在 Attendance.new(attendance_params) 之后打印 member_ids) :

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

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

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您正在尝试批量添加出勤率,为此您可以做 2 件事,

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多