我有一个新表的迁移:
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
当我尝试使用选项create
或find_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">
find_or_create_by
的结果相同:
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.
出了什么问题?如何解决?
信息:
更新:我忘记了attr_accessible:
class ContentCategory < ActiveRecord::Base
# attr_accessible :title <- I forgot to add this line, oh
end
答案 0 :(得分: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