ruby-on-rails - 在 activerecord 中设置默认整数值

标签 ruby-on-rails activerecord migration default-value

因此,我试图将“投票”列的默认值设置为 0,但是当我在 rails c 中或通过单元测试创​​建答案实例时,投票值始终为 nil .关于为什么这不起作用的任何想法?

我已经像这样改变了迁移:

class AddVotesToAnswers < ActiveRecord::Migration
  def change
    add_column :answers, :votes, :integer, default: 0
  end
end

这是模型:
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

测试规范

需要'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

最佳答案

default必须在您运行迁移时设置数据库迁移 - 创建表后添加默认值将不起作用。

如果您的数据库已经播种(并且您不想更改架构),则 ActiveRecord 中的以下 Hook 将完成这项工作:

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

编辑:

如果要更改数据库中的实际默认值,可以创建包含以下内容的更改迁移:
# 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

某些数据库(例如 Postgres)不会自动将新更新的默认值分配给现有列条目,因此您需要遍历现有答案以手动将每个答案更新为默认投票计数:
# in console
Answer.update_all(votes: 0)

关于ruby-on-rails - 在 activerecord 中设置默认整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17016024/

相关文章:

php - 为什么 'php artisan migrate' 命令会创建迁移表以及我打算创建的表?

php - 迁移期间 Laravel 未知数据库错误

ruby-on-rails - 具有强参数的 Rails 4 API?

ruby-on-rails - NoMethodError : undefined method `spec' for nil:NilClass - active_utils, factory_girl 和更多 gems 失败

ruby-on-rails - 为什么belongs_to/has_many 和 inverse_of 不能自动水合另一边?

ruby-on-rails - 重命名作为基类子类的 ActiveRecord 模型时如何迁移数据库?

c# - 具有现有数据库 View 的 Entity Framework 代码优先

ruby-on-rails - 我们如何在 Rails Mailer 中设置电子邮件发件人的名称?

ruby-on-rails - Rails 5.2.3 中的 csp_meta_tag 是什么,它是如何工作的?

ruby-on-rails-3 - Rails 3 验证唯一性忽略模型上的默认范围