如何防止Rails在帖子上创建空行

Tim*_*sen 2 ruby ruby-on-rails ruby-on-rails-4

我有我的迁移:

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
Run Code Online (Sandbox Code Playgroud)

create我的控制器中有我的方法:

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

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

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

PS如何在成功创作时返回成功200响应,而不是 render :nothing => true

teb*_*oso 5

检查模型验证:

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

但作为一个例子:

class Library < ActiveRecord::Base
  has_many :books
  validates_associated :books
end
Run Code Online (Sandbox Code Playgroud)