Setting default values ​​to activerecord

So, I'm trying to set the default value of the "votes" column to 0, but when I instantiate responses in rails c or through unit tests, the value of the votes is always nil . Any ideas on why this is not working?

I changed the migration as follows:

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

Here is the model:

 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 

Testing

spec_helper required

 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 
+6
source share
2 answers

default for database migration must be set during the migration start - adding a default value after creating the table will not work.

If your database has already been carved (and you do not want to change the scheme), the following capture in ActiveRecord will perform the task:

 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 

EDIT:

If you want to change the actual default value in the database, you can create a migration of changes containing the following:

 # 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 

Some databases (such as Postgres) do not automatically assign new updated default values ​​to existing column entries, so you need to iterate over existing answers to manually update each one before the default vote count:

 # in console Answer.update_all(votes: 0) 
+10
source

You should say it like: add_column :answers, :votes, :integer, :default => 0

+1
source

Source: https://habr.com/ru/post/946914/


All Articles