0

I'm working with a legacy database where a story belongs_to a user and a user has_many stories. The problem is that it's all uploaded data, so they can't connect with the id field like Rails usually does.

Here's the structure for the Story table:

  create_table "stories", force: :cascade do |t|
    t.string "title"
    t.integer "authorId"
    ...
  end

And here's the structure for the User table:

create_table "users", force: :cascade do |t|
    ...
    t.integer "uid"
    ...
end

I need to somehow join them so that the story's authorId connects to matching values for a user's uid.

I've looked at questions like this and this, as well as the documentation, but I can't find model code that works.

Right now what I have is, for story.rb:

class Story < ApplicationRecord
    belongs_to :user, class_name: 'User', foreign_key: 'authorId'
end

And for user.rb (I'm using Devise.):

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, and :omniauthable
  devise :database_authenticatable, :registerable, :trackable,
         :recoverable, :rememberable, :validatable

  has_many :stories, class_name: "Story", foreign_key: 'uid'
end

Can anyone see how to get these models properly linked up in a belongs_to/has_many?

Liz
  • 1,369
  • 2
  • 26
  • 61

1 Answers1

1

I believe by your post that you cannot update the AuthorID to user_id, and change uid to id. After that, you would have a clean relationship.

But, try to define the primary_key and foreign_key and customize your association:

class Story < ApplicationRecord
 belongs_to :user, primary_key: "uid", foreign_key: "authorId"
end

class User < ApplicationRecord
  has_many :stories, primary_key: "authorId"
end

or this:

class Story < ApplicationRecord
 belongs_to :user, primary_key: "uid"
end

class User < ApplicationRecord
  has_many :stories, primary_key: "authorId", foreign_key: "uid"
end

I think this maybe works.

Rafael Moreira
  • 176
  • 1
  • 11