V
V
Vladislav Sofienko2017-04-02 19:55:41
Ruby on Rails
Vladislav Sofienko, 2017-04-02 19:55:41

How to implement such structure in rails migration?

How to implement such structure in rails migration?
1. Users and News
table 2. Set Users table to primary key Login with String type
3. Associate Users with News as one-to-many on Login field with String type
52b5fd8bca0d46d58070988673726f50.JPG

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Karim Kyatlottyavi, 2017-04-03
@sofvlad

Try something like this.

class News < ActiveRecord::Base
  belongs_to :user, foreign_key: :login, primary_key: :login
end

class User < ActiveRecord::Base
  has_many :news, foreign_key: :login, primary_key: :login
end

Migrations
class CreateNews < ActiveRecord::Migration
  def up
    create_table :news do |t|
      t.string :login, limit: 50
      t.timestamps null: false
    end
    add_foreign_key :news, :users, column: :login
  end

  def down
    remove_foreign_key :news, name: :login
    drop_table :news
  end
end

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users, id: false, primary_key: :login do |t|
      t.string :login, limit: 50, null: false
      t.timestamps null: false
    end
  end
end

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question