0

I am facing a challenge in RoR that is beyond my understanding. This is a scenario, but it corresponds to the problem I have to solve for a Rails app already in production with thousands of users.

Say I have a model (in truth, I have many models which have this problem, but the issue should be similar?)

Class User << ApplicationRecord
#and the logic here
end

# with the following schema

  create_table "users", force: :cascade do |t|
    t.string "name", null: false
    t.string "description", null: false
    #and more
  end

But now, I have implemented a much nicer description on my Frontend, which uses a nice HTML wisiwig. So I created methods for sanitizing the content etc. After a while, I now need to have so many functions added to this description field, that it becomes cumbersome to maintain it as a string in the DB !

I want to create a Text Model that can keep all of those, so that I can reuse it accross many Models in my app via polymorphic association

So what I want is to have

Class User << ApplicationRecord
has_one :description, as :textable
# and some more logic
end

Class Text << ApplicationRecord
# Here goes the whole text logic, auto translation etc etc
belongs_to :textable, :polymorphic => true
end

# with the following schema

create_table "users", force: :cascade do |t|
  t.string "name", null: false
  #and more
end

create_table "texts", force: :cascade do |t|
  t.string "textable_type"
  t.bigint "textable_id"
  t.string "content"
  #and more
end

How do I change this AND transfer the content of User.description to a new reccord of Text, that I then attach as description

I am aware I could do this via the console in a painful way, but is there a Rails way to do this ? My gut feeling tells me that this could be done in the migrations ?

Thanks !

Xqua
  • 1
  • 1
  • See if this question helps: https://stackoverflow.com/questions/6135600/how-do-i-move-a-column-with-contents-to-another-table-in-a-rails-migration – Abhinay Mar 31 '20 at 13:37
  • So I can add ruby code to migrations ! with the self.up ! Awesome thanks a lot ! – Xqua Mar 31 '20 at 16:55
  • Yes you can, but if you read the answer it says, using Ruby to migrate the record is painfully slow hence you might wanna use the second option which is `execute "UPDATE users u, profiles p SET u.someprop=p.someprop WHERE u.id=p.user_id" ` this is also mentioned in the same answer – Abhinay Apr 01 '20 at 04:35

0 Answers0