Associations can be defined in the initializer file, and when Arql starts, it first generates the model class based on the database schema and then loads the initializer file.
The initializer file is a Ruby file, so you can define associations within it, for example:
module Blog
class Student
has_many :courses, foreign_key: :student_id, class_name: 'Course'
belongs_to :school, foreign_key: :school_id, class_name: 'School'
has_and_belongs_to_many :teachers, join_table: 'students_teachers', foreign_key: :student_id, association_foreign_key: :teacher_id, class_name: 'Teacher'
end
class Course
belongs_to :student, foreign_key: :student_id, class_name: 'Student'
end
class School
has_many :students, foreign_key: :school_id, class_name: 'Student'
end
class Teacher
has_and_belongs_to_many :students, join_table: 'students_teachers', foreign_key: :teacher_id, association_foreign_key: :student_id, class_name: 'Student'
end
end
has_one
Indicates that this table is a one-to-one relationship with the ownerbelongs_to
Indicates that this table is a subordinate of a one-to-many or one-to-one relationshiphas_and_belongs_to_many
Indicates that this table is one of the parties to a many-to-many relationshipclass_name
The model class name of the other party that indicates the relationship (the model class name is actually the CamelCase form of the table name)foreign_key
Indicates the name of the associated field on the side of the dependent table in the associationprimary_key
Indicates the name of the association field on the side of the master table in the associationjoin_table
In a many-to-many relationship, the name of the intermediate table that is associated with two tables is indicatedassociation_foreign_key
In a many-to-many relationship, indicates the name of the field associated with the other model’s model in the intermediate table
可以参考: https://guides.rubyonrails.org/association_basics.html
Considering that the model classes are all defined under the Namespace module, a blog here is necessary.
Of course, Arql will load the ~/.arql.rb
OR ~/.arql.d/init.rb
file by default, regardless of which environment is
selected via the -e
options, so putting a fixed namespace Blog
in the default initialization file like in the
example above is not a good choice.
There are two ways to solve this problem:
1.
When using arql, for different environments, use -i
the option to specify different initialization files, such as:
arql -e blog -i ~/.arql.d/blog.rb
- Refer to Put the initialization code for different environments in different files