加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – rails3 default_scope,以及迁移中的默认列值

发布时间:2020-12-16 20:50:12 所属栏目:百科 来源:网络整理
导读: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 sel
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,为什么?

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

wojciech @ vostro:?/ work / ze $rails console
加载开发环境(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>

解决方法

The documentation fordefault_scope表示提供的范围适用于查询和新对象.模型级别提供的缺省值始终优先于模式级别提供的缺省值,因为它们是在将数据发送到数据库之前在应用程序内部创建的.

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

Crew.unscoped.new

* ActiveRecord模糊了数据库(模式)中定义的默认值与应用程序(模型)中的默认值之间的差异.在初始化期间,它解析数据库模式并记录其中指定的任何默认值.稍后,在创建对象时,它会分配这些模式指定的默认值,而不会触及数据库.例如,您将在Crew.unscoped.new的结果中看到已批准:false(而不是approved:nil),即使数据从未发送到数据库以使其填写其默认值(ActiveRecord抢先填写)默认值基于它从架构中提取的信息).

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读