Doge
Doge

Reputation: 387

Rails - Change default value on alternate new data columns

this is a Rails 4 + MySQL, but perhaps a general logic question. I did not find even a related topic to this (only Frontend A/B testing), so apologies if there is somehow a related question.

I would like to do an A/B test but with persistent data.

Consider a new user registration, where one of the columns (let's call it test) in the table is a boolean and each new registration saves a different boolean state to the new DB row on the user's table on each new user registration.

User 1 registers -> test value in User1 row is false

User 2 registers -> test value in User2 row is true

User 3 registers -> test value in User3 row is false

User 4 registers -> test value in User4 row is true

And so on...

Is there a way to achieve this in Rails? Or is this a DB/MySQL issue?

Thanks!

Upvotes: 1

Views: 25

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

I can see 2 options: use Rails' callback before_create (or before_validation) or use a MySQL trigger before INSERT.

Rails Callback:

before_create do
  self.test = !User.order(:id).last&.test.present?
end

Upvotes: 1

Related Questions