rails3 default_scope,以及迁移中的默认列值 [英] rails3 default_scope, and default column value in migration

查看:21
本文介绍了rails3 default_scope,以及迁移中的默认列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class CreateCrews < ActiveRecord::Migration
  def self.up
    create_table :crews do |t|
      t.string :title
      t.text :description
      t.boolean :adult
      t.boolean :private
      t.integer :gender_id
      t.boolean :approved, :default => false
      t.timestamps
    end
  end
  def self.down
    drop_table :crews
  end
end


class Crew < ActiveRecord::Base
  has_many :users, :through => :crew_users
  belongs_to :user

  default_scope where(:approved => true)
end

当我进入控制台并创建新记录时,已批准"属性设置为 true,为什么?

When I go to console, and create a new record, the "approved" property is set to true, why ?

如何自动将其设置为默认值 (false),如迁移文件中所示?

How I can set it automatically to the default value (false) like shown in my migration file ?

wojciech@vostro:~/work/ze$ rails 控制台加载开发环境(Rails 3.0.0)ruby-1.9.2-p0 >c = Crew.new<代码>=>#<船员ID:无,标题:无,描述:无,成人:无,私人:无,gender_id:无,批准:true,created_at:无,updated_at:无,logo_file_name:无,logo_content_type:无,logo_file_size:nil, logo_updated_at: nil>

推荐答案

default_scope 的文档说提供的范围适用于查询和新对象.在模型级别提供的默认值将始终优先于在架构级别提供的默认值,因为它们是在数据发送到数据库之前在应用程序内部创建的.

The documentation fordefault_scope says that the provided scope is applied to both queries and new objects. Default values supplied at the model level will always take precedence over defaults provided at the schema level because they are made inside the application before the data is ever sent to the database.

您可以使用 unscoped 暂时跳过所有范围(包括 default_scope).这应该允许较低级别的数据库默认机制生效*.

You can use unscoped to temporarily skip all scoping (including the default_scope). This should allow the lower level database defaulting mechanism to take effect*.

Crew.unscoped.new

<支持>*ActiveRecord 掩盖了在数据库(模式)中定义的默认值和在应用程序(模型)中完成的默认值之间的区别.在初始化期间,它解析数据库模式并记录那里指定的任何默认值.稍后,在创建对象时,它会分配那些模式指定的默认值,而不涉及数据库.例如,您将在 Crew.unscoped.new 的结果中看到 approved: false(而不是 approved: nil),即使数据从未发送到数据库以使其填写其默认值(ActiveRecord 根据从架构中提取的信息抢先填写默认值).

*ActiveRecord obscures the difference between defaulting defined in the database (schema) and defaulting done in the application (model). During initialization, it parses the database schema and notes any default values specified there. Later, when creating objects, it assigns those schema-specified default values without touching the database. For example, you will see approved: false (instead of approved: nil) in the result of Crew.unscoped.new even though the data has never been sent to the database to get it to fill in its default value (ActiveRecord preemptively fills in the default value based on information it pulled out of the schema).

这篇关于rails3 default_scope,以及迁移中的默认列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆