I have studied several questions on this topic today. I know that, I can use t.references
in migration to add a reference. But, If a table has non-integer primary key, how do I add reference to that column?
I have a table with this definition
create_table :sessions, id: false do |t|
t.string :session, primary_key: true, limit: 10
t.timestamps null: false
end
How do I add a reference to the session
column (the name doesn't matter here), which is a string from another table migration. I tested with t.references
but that just add an integer column. I know that I can use add column
. But how to do that without from create_table
method directly?
Clarification for duplicate flag
This question is flagged as duplication of this question, but it is actually not. Because I am not asking about setting up table with non-default non-integer primary key, because I already set up that table. I am asking about referencing this type of table from another table.
Since rails version 4.2.7
You can specify type
into the add_reference
helper.
Suppose you have table records
and you want to have reference of sessions
inside records
. Then you can do the following :
add_reference :records, :sessions, type: :string, foreign_key: {to_table: :sessions, primary_key: :session}
Rather than using the references helper, you would need to use the string type, and add an index for faster lookups. If your other model is "Record":
rails generate migration AddSessionIdToRecords session:string:index
Which should generate a migration like so:
def change
add_column :records, :session_id, :string
add_index :records, :session_id
end
Since you're using unconventional naming, you'd need to specify the primary key in the model and the relation definition:
class Session < ActiveRecord::Base
self.primary_key = "session"
has_many :records, primary_key: "session"
end
class Record < ActiveRecord::Base
belongs_to :session, primary_key: "session"
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With