Kei*_*son 7 migration activerecord ruby-on-rails default-value
所以我试图将'votes'列的默认值设置为0,但是当我在rails c或单元测试中创建答案的实例时,投票值总是如此nil
.关于为什么这不起作用的任何想法?
我这样改变了迁移:
class AddVotesToAnswers < ActiveRecord::Migration
def change
add_column :answers, :votes, :integer, default: 0
end
end
Run Code Online (Sandbox Code Playgroud)
这是模型:
class Answer < ActiveRecord::Base
attr_accessible :is_correct, :question_id, :title, :sms_answer_code, :votes
belongs_to :question
def upvote
self.votes += 1
end
end
Run Code Online (Sandbox Code Playgroud)
测试规格
需要'spec_helper'
describe Answer do
before do
@answer = Answer.make!
end
it "should have a default vote value of zero" do
binding.pry
@answer.votes.should eq(0)
end
end
Run Code Online (Sandbox Code Playgroud)
zea*_*soi 10
该default
添加一旦表已创建将无法正常工作的默认值-为DB迁移必须在您运行迁移时设置.
如果您的数据库已经播种(并且您不想更改架构),则ActiveRecord中的以下挂钩将完成此任务:
class Answer < ActiveRecord::Base
attr_accessible :is_correct, :question_id, :title, :sms_answer_code, :votes
belongs_to :question
before_save :default_vote_count
def upvote
self.votes += 1
end
def default_vote_count
self.votes ||= 0
end
end
Run Code Online (Sandbox Code Playgroud)
编辑:
如果要更改数据库中的实际默认值,可以创建包含以下内容的更改迁移:
# in console
rails g migration change_default_for_answer_votes
# in migration file
class ChangeDefaultForAnswerVotes < ActiveRecord::Migration
def change
change_column :answers, :votes, :integer, :default => 0
end
end
Run Code Online (Sandbox Code Playgroud)
某些数据库(例如Postgres)不会自动为现有列条目分配新更新的默认值,因此您需要迭代现有答案以手动将每个更新为默认的投票计数:
# in console
Answer.update_all(votes: 0)
Run Code Online (Sandbox Code Playgroud)