【发布时间】: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