简体   繁体   中英

How does Rails know which column from a table is the index in a related table?

The syntax for the has_many , belongs_to , etc. data schema modifiers don't require the specification of a column identifier to make the association. How does Rails infer the relations between tables? Examples I've seen all use the convention <table_name>_id in the tables that have an external relation: is this more than just a common practice?

Ruby on Rails use "convention over configuration" pattern ( convention over configuration ). For has_many association, for example, there should be foreign_key (without it there is no way to understand how to link things), by default it is model_name_id column, but you can specify it (here info about association basics ).

So you may have Category and Article models linked by has_many association, by default active_record will look for category_id column in articles table, but you may have cat_id column instead, and just write:

# in category model
has_many :articles, :class_name => 'Article', :foreign_key => "cat_id"
# in article model
belong_to :category, :class_name => 'Category', :foreign_key => "cat_id"

This looks like rails 'magic' but is just an assumption that ActiveRecord makes

4.1.2.6 :foreign_key

By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly:

Source: http://guides.rubyonrails.org/association_basics.html

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