尝试提交包含文件的表单时出现错误“分配必须存在”。
我将分配参数传递给表单,检查强参数,仍然要求assignment_id
。我尝试在分配标记模型上使用:optional
,但是它将assignment_id
列留空,这不是我想要的。
使用检查之后,我发现它没有将assignment_id
和file
传递给create
动作。
AssignmentMark模型
class AssignmentMark < ApplicationRecord
mount_uploaders :file, AssignmentMarkUploader
serialize :file, JSON
belongs_to :assignment
belongs_to :user
end
我有一个链接,该链接传递了assignment_id值
#assignments/show.html.erb
<%= link_to 'Add new submission', new_assignment_mark_path(assignment: @assignment), class: "btn btn-primary" if @user_assignment.blank? %>
在我的assignment_mark_controller.erb中,我有新建和创建方法
def new
@assignment = Assignment.find(params[:assignment])
@assignment_mark = AssignmentMark.new(assignment_id: params[:assignment])
end
def create
@assignment_mark = AssignmentMark.new(assignment_mark_params)
@assignment_mark.user_id = current_user.id if current_user
respond_to do |format|
if @assignment_mark.save
format.html { redirect_to assignment_path(@assignment_mark), notice: 'Assignment mark was successfully created.' }
format.json { render :show, status: :created, location: @assignment_mark }
else
format.html { render :new }
format.json { render json: @assignment_mark.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_assignment_mark
@assignment_mark = AssignmentMark.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def assignment_mark_params
params.require(:assignment_mark).permit(:marks, :user_id, {file: []}, :assignment_id)
end
end
在我的assign_mark表单视图中(使用脚手架生成的表单)
<div class="form-group ">
<%= form.label :file %>
<%= form.file_field :file, autofocus: true, required: true, multiple: true, class: "form-control" %>
</div>