代码之家  ›  专栏  ›  技术社区  ›  astropanic

rails3默认范围和迁移中的默认列值

  •  10
  • astropanic  · 技术社区  · 14 年前
    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
    

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

    wojciech@vostro:~/work/ze$ rails console Loading development environment (Rails 3.0.0) ruby-1.9.2-p0 > c = Crew.new => #<Crew id: nil, title: nil, description: nil, adult: nil, private: nil, gender_id: nil, approved: true, created_at: nil, updated_at: nil, logo_file_name: nil, logo_content_type: nil, logo_file_size: nil, logo_updated_at: nil>

    2 回复  |  直到 14 年前
        1
  •  12
  •   Chris Johnsen    14 年前

    The documentation for default_scope 表示提供的作用域同时应用于查询和新对象。在模型级别提供的默认值始终优先于在架构级别提供的默认值,因为它们是在数据发送到数据库之前在应用程序中生成的。

    unscoped 暂时跳过所有作用域(包括 默认范围 *

    Crew.unscoped.new
    

    *ActiveRecord隐藏了在数据库(模式)中定义的默认值和在应用程序(模型)中完成的默认值之间的区别。在初始化过程中,它解析数据库架构并记录其中指定的任何默认值。稍后,在创建对象时,它会在不接触数据库的情况下指定那些架构指定的默认值。例如,您将看到 approved: false (而不是 approved: nil )结果是 Crew.unscoped.new

        2
  •  1
  •   Pioz    9 年前

    一个小技巧是

    default_scope -> { where('crews.approved = 1') }