簡體   English   中英

鐵路中多條路線的一項行動

[英]One action for multiple routes in rails

我是使用Rails創建Web的新用戶。 我在路線欄桿上遇到問題。 我有3個模型。 StudentTeacherClass

Student 
  has_many class

Teacher
  has_many class

Class
  belongs_to student
  belongs_to teacher

在routes.rb中:

resources: students do
  resources: classes
end

resources: teachers do
  resources: classes
end

我打電話時出現問題

students/1/classes or teachers/1/classes

他們倆都打電話

類控制器中的動作索引

我的目的是顯示數據類取決於老師ID,數據類取決於學生ID

調用時如何創建差異

類控制器中的動作索引

謝謝

檢查以下參數是否存在:

def index
  if params[:student_id]
     @object = Student.find(params[:student_id])
  else
     @object = Teacher.find(params[:teacher_id])
  end
  @classes = @object.classes
end

您有兩個選擇:

  1. 確定路線本身中的選項
  2. 使用條件邏輯識別控制器中的數據

實際上,這兩種方法都將使用條件邏輯-它僅取決於您將使用哪種方法來確定如何確定輸出:

#config/routes.rb
resources :students do
   resources :classes, model: "Student"
end

resources :teachers do
   resources :classes, model: "Teacher"
end

#app/controllers/classes_controller.rb
class ClassesController < ApplicationController
   before_action :set_parent, only: :index

   def index
      # @classes will already be set!
   end

   private

   def set_parent
      id = params[:student_id] || params[:teacher_id]
      if params[:model].exists?
         model = params[:model]
      else
         model = "Student" if params[:student_id]
         model = "Teacher" if params[:teacher_id]
      end
      @model = model.constantize
      @parent = @model.find id
      @classes = @parent.send model.lowercase.pluralize
   end
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM