How can I assign different table name with adding foreign key. for e.g
I have a model like
class MyPost < ActiveRecord::Base
has_many :comments, class_name: PostComment
end
class PostComment < ActiveRecord::Base
belongs_to :post, class_name: MyPost
end
Now i want to change my migration file like this:
class CreatePostComments < ActiveRecord::Migration
def change
create_table :post_comments do |t|
t.belongs_to :post, index: true
t.timestamps null: false
end
add_foreign_key :post, :class_name => MyPost
end
end
But it is not working. Migration is getting cancelled. How do I change my migration file to work with my model structure.
You can pass in options for the foreign key as following:
This is also true for the index option if you like to add a unique constraint:
By the way, references is an alias for
belongs_to
, or to be more exact,belongs_to
is an alias for references.See the details in the implementation rails 5.0.rc2 & rails 4.2
It should look like this:
Take a look at the documentation: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_foreign_key
You use the
column
option when the column is named differently.