【问题标题】:How to prevent Rails from creating empty rows on post如何防止 Rails 在帖子上创建空行
【发布时间】:2014-06-19 21:59:51
【问题描述】:

我有我的迁移:

class CreateCourses < ActiveRecord::Migration
  def change
    create_table :courses, :id => false do |t|
      t.uuid :id, :primary_key => true, :null => false
      t.datetime :date_start, :null => false
      t.float :price, :null => false
      t.datetime :date_end
      t.text :description
      t.text :location, :null => false
      t.timestamps
    end
  end
end

我的控制器中有 create 方法:

def create
  course  = Course.new(params[:course])
  if course.save
    render :nothing => true
  else
    render "public/422", :status => 422
    return
  end 
end

现在,当我使用任何数据调用我的create 方法时,它会在我的Course 表中创建一个新的空行。但是我想确保发送来创建的对象实际上是一个 Course 对象,并且位置和价格(例如)不为空且存在。

我有 ASP.NET MVC 背景,所以我刚刚开始学习 Rails。

P.S 如何在成功创建时返回成功 200 响应,而不是 render :nothing =&gt; true

【问题讨论】:

标签: ruby-on-rails ruby ruby-on-rails-4


【解决方案1】:

检查模型验证:

http://guides.rubyonrails.org/active_record_validations.html#validates-associated

但作为一个例子:

class Library < ActiveRecord::Base
  has_many :books
  validates_associated :books
end

【讨论】:

    【解决方案2】:

    通常,您希望在模型中进行验证,以确保您不会创建无效的记录,例如:

    class Course < ActiveRecord::Base
      ...
      validates :location, :price, presence: true
      ...
    

    在返回成功响应方面,您可能想要做的是在完成处理后重定向到 show 页面,例如:

    def update
      respond_to do |format|
        if @course.save
          format.html { redirect_to @course, notice: 'Course was successfully created.' }
        end
      end
    end
    

    另外,运行代码以在控制器中的方法中获取对象也是一个好主意,这意味着代码重复更少!:

    class CourseController < ApplicationController
      before_action :set_course
      ...
    
      def set_course
        @course = Course.find(params[:id])
      end
      ...
    

    【讨论】:

    • 我正在使用 angularJS 作为前端,所以我“需要”返回成功响应
    • 根据:shellycloud.com/blog/2013/10/… 看起来你应该这样做 render nothing: true, status: 200 顺便说一句,这些天写render nothing: true 比写render :nothing =&gt; true 好得多,我个人认为它读起来好多了
    猜你喜欢
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-17
    • 2012-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多