Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

passing unique parameter to belongs_to wrongly #28265

Merged
merged 1 commit into from
Mar 4, 2017
Merged

passing unique parameter to belongs_to wrongly #28265

merged 1 commit into from
Mar 4, 2017

Conversation

0oneo
Copy link
Contributor

@0oneo 0oneo commented Mar 3, 2017

passing unique parameter to belongs_to not right

Summary

the original code can't generate unique index:

create_table :accounts do |t|
  t.belongs_to :supplier, index: true, unique: true, foreign_key: true
  # ...
end

the generated schema.rb is:

create_table "accounts", force: :cascade do |t|
    t.string   "account_number"
    t.integer  "supplier_id"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.index ["supplier_id"], name: "index_accounts_on_supplier_id"
 end

when change the migration code to:

create_table :accounts do |t|
      t.string :account_number
      t.belongs_to :supplier, index: { unique: true }, foreign_key: true

      t.timestamps
end

the result is right:

create_table "accounts", force: :cascade do |t|
    t.string   "account_number"
    t.integer  "supplier_id"
    t.datetime "created_at",     null: false
    t.datetime "updated_at",     null: false
    t.index ["supplier_id"], name: "index_accounts_on_supplier_id", unique: true
end

passing `unique` parameter to belongs_to not right,
@0oneo
Copy link
Contributor Author

0oneo commented Mar 3, 2017

BTW, from the generated result, I don't quite get the meaning of foreign_key: true optional parameter

@sevenseacat
Copy link
Contributor

It adds a database-level foreign key between the tables. After running the migration your schema.rb should have an add_foreign_key line at the bottom of it.

@0oneo
Copy link
Contributor Author

0oneo commented Mar 3, 2017

@sevenseacat I have located the release notes of 4.2, it saids "only the mysql, mysql2 and postgresql adapters support foreign keys"

@sevenseacat
Copy link
Contributor

that's correct.

@kamipo kamipo merged commit 64b797d into rails:master Mar 4, 2017
@kamipo
Copy link
Member

kamipo commented Mar 4, 2017

Thanks!

In the future, please add [ci skip] to any commits that involve changing the documentation, to avoid running the entire Rails test suite.

@0oneo 0oneo deleted the association_guide branch March 4, 2017 10:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

4 participants