답변

0

Rails 애플리케이션에서 사용 된 규칙에 익숙해지는 것이 좋습니다. 또한 ActiveRecord의 모든 기능을 사용할 수 있도록 모델 내에서 관계를 올바르게 정의했는지 확인하십시오. 나는 당신의 관계에서 추측을 만들고 있어요,하지만 난이 꽤 정확한 표현입니다 같은데요 :

+------------+    +-----------------+    +------------+ 
| Teachers |-|-----------|<| Subscriptions |>|---------|-| Subjects | 
+------------+    +-----------------+    +------------+ 

모델

# app/models/subject.rb 
class Subject 
    has_many :subscriptions 
    has_many :teachers, through: :subscriptions 
end 

# app/models/teacher.rb 
class Teacher 
    has_many :subscriptions 
    has_many :subjects, through: :subscriptions 

    def display_name 
    "#{self.surname} #{self.name}" 
    end 
end 

# app/models/subscription.rb 
class Subscription 
    belongs_to :teacher 
    belongs_to :subject 
end 

컨트롤러

# app/controllers/subscriptions_controller.rb 

class SubscriptionsController < ApplicationController 
    def index 
     @subscriptions = Subscription.includes(:teacher, :subject).order("courses.name ASC").all 
    end 
end 

보기

# app/views/subscriptions/index.html.erb 
<table> 
    <thead> 
    <tr> 
     <th>Course</th> 
     <th>Teacher</th> 
    </tr> 
    </thead> 
    <tbody> 
    <%= content_tag_for :tr, @subscriptions do |subscription| %> 
     <td><%= subscription.subject.name %></td> 
     <td><%= subscription.teacher.display_name %></td> 
    <% end %> 
    </tbody> 
</table> 
관련 문제