![](/img/trans.png)
[英]Rails3 ActiveRecord and custom SQL JOINS with default_scope
[英]rails3 default_scope, and default column value in migration
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 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>
default_scope
的文檔說明提供的范圍適用於查詢和新對象。 模型級別提供的缺省值始終優先於模式級別提供的缺省值,因為它們是在將數據發送到數據庫之前在應用程序內部創建的。
您可以使用unscoped
暫時跳過所有作用域(包括default_scope
)。 這應該允許較低級別的數據庫默認機制生效* 。
Crew.unscoped.new
* ActiveRecord模糊了數據庫(模式)中定義的默認值與應用程序(模型)中的默認值之間的差異。 在初始化期間,它解析數據庫模式並記錄在那里指定的任何默認值。 稍后,在創建對象時,它會分配這些模式指定的默認值,而不會觸及數據庫。 例如,您將在Crew.unscoped.new
的結果中看到approved: false
(而不是approved: nil
),即使數據從未被發送到數據庫以使其填充其默認值(ActiveRecord搶占式填寫)默認值基於它從架構中提取的信息)。
一個小技巧是使用
default_scope -> { where('crews.approved = 1') }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.