ruby on rails - Foreign key in active record’s self-referential has_many :through -


i'm using rails 4 schema_plus gem.

i want able access models way:

    phrase = phrase.create(name:'car')     another_phrase = phrase.create(name:'vehicle')     phrase.synonym_phrases << another_phrase     p phrase.synonym_phrases 

my relationship setup:

    class phrase < activerecord::base       has_many :synonyms       has_many :synonym_phrases, through: :synonyms     end      class synonym < activerecord::base       belongs_to :phrase       belongs_to :synonym_phrase, class_name: 'phrase', foreign_key: :synonym_id     end 

after migratind database, generated schema looks this:

    activerecord::schema.define(version: 20141211103911)        create_table "phrases", force: true |t|         t.string   "name"         t.datetime "created_at"         t.datetime "updated_at"       end        create_table "synonyms", force: true |t|         t.integer  "phrase_id"         t.integer  "synonym_id"         t.datetime "created_at"         t.datetime "updated_at"         t.index ["phrase_id"], :name => "fk__synonyms_phrase_id"         t.index ["synonym_id"], :name => "fk__synonyms_synonym_id"         t.foreign_key ["phrase_id"], "phrases", ["id"], :on_update => :no_action, :on_delete => :no_action, :name => "fk_synonyms_phrase_id"         t.foreign_key ["synonym_id"], "synonyms", ["id"], :on_update => :no_action, :on_delete => :no_action, :name => "fk_synonyms_synonym_id"       end 

in second foreign key assigment wrong, because points synonyms table, instead pointing phrases table (self-referentiall).

i found out, adding foreign_key: { references: :phrases } migration solves problem.

    # db/migrate/20141211103911_create_synonyms.rb     class createsynonyms < activerecord::migration       def change         create_table :synonyms |t|           t.integer :phrase_id           t.integer :synonym_id, foreign_key: { references: :phrases }            t.timestamps         end       end     end 

after database drop , migrate schema generated correctly.

    # db/schema.rb     -    t.foreign_key ["synonym_id"], "synonyms", ["id"], :on_update => :no_action, :on_delete => :no_action, :name => "fk_synonyms_synonym_id"     +    t.foreign_key ["synonym_id"], "phrases", ["id"], :on_update => :no_action, :on_delete => :no_action, :name => "fk_synonyms_synonym_id" 

i'm curious there way of setting relationship without editing migration files? maybe other naming convention in models? ideas?


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -