ruby on rails - What is the process of creating a joining table which resolves a many-to-many relationship using migrations? -


i understand process can followed create models , migrations in turn create joining table within database resolve many-to-many relationship. instance. if have course table, students table , want create joining table called studies id course , students along data such grade , date started. process doing this? if use generate model command each of above 3 table names, create separate migration of them. if go models , add relevant associations not affect how database created? please give me guidance on steps must take in order create required foreign key relationships here examples?

use has_many :through association. set manually.

step 1: generate models separately. joining model study contain foreign keys, remember include columns.

rails g model course title:string rails g model student name:string rails g model study course_id:integer student_id:integer start_date:date grade:string   

step 2: set associations:

# models/course.rb class course   has_many :studies   has_many :students, through: :studies end  # models/student.rb class student   has_many :studies   has_many :courses, through: :studies end  # models/study.rb class study   belongs_to :course   belongs_to :student end 

step 3: run migrations, restart server (if necessary), , that's it. rails handle rest.

accessing attributes in joining table may require careful timing ensure correct object being accessed, since joining object not returned via rails' built-in methods, ie @course.students. check out this answer ideas.

read guide more information.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -