简体   繁体   中英

Placing the foreign key in rails model belongs_to association

I am a beginner to rails framework. I have a fundamental question.

I am trying to define some models and their association referring the popular rails guides. My association looks like below.

class Person < ActiveRecord::Base
  has_one :head
end

class Head < ActiveRecord::Base
  belongs_to :person
end

Here, I need to add the foreign_key (Persons's primary key) in the table 'head'.

Now, if I need to get the 'head' of a 'person', rails need to scan through the head table and match the person_id.

The straight forward way I would think is to add the foreign key in 'person' table. Then I can directly refer the 'head' from 'person' with it's ID.

It appears that rails convention is not performance friendly. Am I missing something here?

When you create the migration to add the column containing the foreign key, it is highly recommended to add an index on this column. This way, the database will efficiently find the Head from the person_id (as efficiently then a search by its id ).

add_index :heads, :person_id

If it's a one-to-one association, you can even add the unique option (unless your application accepts conjoined twins :-) ):

add_index :heads, :person_id, :unique => true

I suggest you to have a look to this 2 articles on where to use indexes:

Re: It appears that rails convention is not performance friendly. Am I missing something here?

Yes. Rails is designed for production sites. So it includes many performance features. As @Baldrick says, the answer to your specific concern is to always add an index for foreign key fields.

Adding an index for each foreign key field is needed, for performance reasons, for any SQL dbms application, no matter the language. Note that the index is added to the database, not to the MVC layers (Rails).

Rails itself includes additional performance features including sql results caching, optional fragment and page caching, and more.

Rails 3.2 includes the slow query features . These enable Rails to automatically show you the queries which are slow. You can then focus on fixing them as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM