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

时间:2014-06-19 21:59:51

标签: ruby-on-rails ruby 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

我的控制器中有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表中创建一个新的空行。但是,我想确保发送给create的对象实际上是一个Course对象,并且位置和价格(例如)不是空的并且存在。

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

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

2 个答案:

答案 0 :(得分:5)

检查模型验证:

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

但作为一个例子:

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

答案 1 :(得分:1)

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

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
  ...
相关问题