2015-06-25 96 views
1

我有新表的遷移覆蓋:的Rails:遷移默認值不能被創建方法

class CreateContentCategories < ActiveRecord::Migration 
    def change 
    create_table :content_categories do |t| 
     t.string :title, default: '', null: false 

     t.timestamps null: false 
    end 
    end 
end 

當我嘗試createfind_or_create_by新記錄的選項:

def self.assign_titles_to_app(titles, app) 
    # somewhere inside (class scope) 
    title = 'movies' 
    content_category = find_by_title(title) || create(title: title) 
    puts "title: #{title} category: #{content_category.inspect}" 

活動記錄不使用我的標題

title: movies category: #<ContentCategory id: 1050, title: "", created_at: "2015-06-25 15:42:57", updated_at: "2015-06-25 15:42:57"> 

的結果相同210:

title = 'movies' 
content_category = find_or_create_by(title: title) 
title: movies category: #<ContentCategory id: 1062, title: "", created_at: "2015-06-25 15:45:25", updated_at: "2015-06-25 15:45:25"> 

文檔說:

:default - The column's default value. Use nil for NULL. 

到底哪裏出問題了?如何解決它?

信息:

  • 軌4.2.1
  • 的ActiveRecord 4.2.1
  • 紅寶石2.2.2

更新:我忘了attr_accessible:

class ContentCategory < ActiveRecord::Base 
# attr_accessible :title <- I forgot to add this line, oh 
end 
+0

在哪個上下文中調用方法find_or_create_by或create?你不應該'ContentCateogry.create(title:title)'? –

+0

@ArslanAli,在類範圍內 – gaussblurinc

+0

您在模型中的'after_save'或'after_create'中是否有任何操作?因爲顯然,你的代碼沒有問題。 –

回答

2

你的代碼沒有問題,也許你需要重新啓動你的應用程序(和彈簧),或者問題出現在你沒有顯示的代碼中。爲了演示,我將你的確切代碼添加到了一個vanilla 4.2應用程序中,並且:

[9] pry(main)> ContentCategory.assign_titles_to_app 1, 2 
    ContentCategory Load (0.2ms) SELECT "content_categories".* FROM "content_categories" WHERE "content_categories"."title" = ? LIMIT 1 [["title", "movies"]] 
    (0.1ms) begin transaction 
    SQL (0.7ms) INSERT INTO "content_categories" ("title", "created_at", "updated_at") VALUES (?, ?, ?) [["title", "movies"], ["created_at", "2015-06-25 16:31:59.192793"], ["updated_at", "2015-06-25 16:31:59.192793"]] 
    (0.5ms) commit transaction 
title: movies category: #<ContentCategory id: 1, title: "movies", created_at: "2015-06-25 16:31:59", updated_at: "2015-06-25 16:31:59"> 
=> nil