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

所以我试图将’Votes’列的认值设置为0,但是当我在rails c或单元测试中创建答案实例时,投票值总是为零.关于为什么这不起作用的任何想法?

我这样改变了迁移:

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

解决方法

必须在运行迁移时设置数据库迁移的认值 – 创建表后添加认值将不起作用.

如果您的数据库已经播种(并且您不想更改架构),则ActiveRecord中的以下挂钩将完成此任务:

class Answer < ActiveRecord::Base
    attr_accessible :is_correct,: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,:default => 0
  end

end

某些数据库(例如Postgres)不会自动为现有列条目分配新更新的认值,因此您需要迭代现有答案以手动将每个更新为认的投票计数:

# in console
Answer.update_all(Votes: 0)

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...