在Rails中,有多个输入源(要创建),输入视图的条件返回有错误吗?

时间:2018-05-10 01:09:45

标签: ruby-on-rails ruby ruby-on-rails-5

我有一个带有两种输入数据方式的应用程序:(1)单入口页面/ form_with字段[aka'input_page']和(2)文件上载页面[aka'file_upload_page']接受包含多个条目的电子表格(此处为学生课程)。

我的目标是在与输入源关联的视图(input_page或file_upload_page)上显示验证错误消息。

课程控制器目前看起来像这样:

def create
  @user = current_user
  @course = (Course.import(params[:course][:file]) || 
    Course.new(course_params))
    # the input is either a file (spreadsheet) or the aforementioned 
    # `form_with` fields 
  @course.save

respond_to do |format|
  if @course.save
    # when successful, both inputs return the same view,
    #  `courses_path` 

    format.html { redirect_to courses_path, notice: '...success!' }
    format.json { render :show, status: :created, location: 
      courses_path }

  else
    # here is where the 'challenge' arises for the single input_page

    format.html { redirect_to input_page, alert: 
      course.errors.full_messages }

    # now, how do I *conditionally* return the file_upload_page if
    # the user uploaded multiple courses with a spreadsheet

    format.html { redirect_to file_upload_page, alert: 
      course.errors.full_messages }
  end

(上传的电子表格文件使用课程模型中的Roo gem进行解析,课程保存,并返回到课程控制器,创建操作。)

目前,(1)成功保存input_page或file_upload_page - 正确 - 返回courses_path。 (2)如果验证失败,则input_page和file_upload_page都返回input_page视图 - 因为该代码首先运行。

我需要else块中的某些内容,如果输入来自X视图,返回带有错误的X视图,否则返回带有错误的Z视图'

1 个答案:

答案 0 :(得分:0)

你的params告诉你它是否是文件上传,所以使用该逻辑来确定错误路径:

def create
  @user = current_user
  @course = Course.import(params[:course][:file]) || Course.new(course_params)
  if @course.save
    respond_to do |format|
      format.html { redirect_to courses_path, notice: '...success!' }
      format.json { render :show, status: :created, location: courses_path }
    end
  else
    errors_path = params[:course][:file] ? file_upload_page : input_page
      respond_to do |format|
        format.html { redirect_to errors_path, alert: course.errors.full_messages }
      end
  end
end