簡體   English   中英

如何有效地管理與關聯模型的多態關聯?

[英]How do I Resourcefully manage a polymorphic association with an associated model?

我正在嘗試執行以下操作:事件可以使單個學生競爭,也可以使一組學生競爭。 因此,我對它進行了多態設置,如下所示:

class Event < ActiveRecord::Base
  belongs_to :event_type
  has_many :competitors
  has_many :students, through: :competitors, :source => :participant, :source_type => 'Student'
end

class Competitor < ActiveRecord::Base
  belongs_to :event
  belongs_to :participant, polymorphic: true

  # also has other attributes, like points, and grade
end

class Student < ActiveRecord::Base
  has_many :competitors, :as => :participant
  has_many :events, :through => :competitors
end

class Team < ActiveRecord::Base
  has_many :competitors, :as => :participant
  has_many :events, :through => :competitors
  has_many :team_members
  has_many :students, :through => :team_members
end

tl; dr:如何使用足智多謀的控制器處理這些?

我已經有一個事件控制器,它使我可以CRUD它的屬性。 我有一個學生控制器,執行相同的操作。 因此,現在我需要“競爭者”控制器來組合它們。 我在這里畫一個空白。

我想要的是能夠從一個學生復選框的列表中選擇一個屏幕上的比賽項目。 如果我創建一個嵌套路由,例如

resources :events, shallow: true do
  resources :competitors, shallow: true
end

然后,我可以轉到events/1/competitors以顯示競爭對手列表。 但是,然后它應該顯示團隊,還是學生? 我不想讓它變成一堆if / elses。 那么我應該為這兩個單獨設置控制器嗎? 他們將如何命名? 我將如何與他們互動?

假設我確實為學生競爭對手制作了一個控制器:

resources :events, shallow: true do
  resources :student_competitors, shallow: true
end

我會得到events/1/student_competitors 這將顯示所有參加該事件的學生的列表。 假設我想通過“更新”按鈕使該列表成為一組復選框。 我將如何構造該表格?

<%= simple_form_for(@event, :html => { :class => 'form-vertical' }) do |f| %>
  <% @students.each do |student| %>
    <%= check_box_tag "event[student_ids][]", student.id, student.events.include?(@event) %>
    <span><%= student.name %></span>
  <% end %>

  <%= f.button :submit, 'Update Competitors' %>
<% end %>

這會將表單提交回events/1 ,而我希望將其提交給StudentCompetitors控制器,但是我無法使用諸如simple_form_for(@event, @competitors)類的集合調用simple_form_for並使其構造路徑進行更新操作。

本質上,我不確定如何最好地完成所有這些工作。 我是否要過於嚴格,堅持使用資源? 感謝您的幫助。

我使用了單個資源:

resources :events, shallow: true do
  resource :student_competitors, shallow: true
end

因此,我可以在events/1/student_competitors編輯學生競爭者,並且將simple_form_for用作:

<%= simple_form_for(:student_competitors, url: event_student_competitors_path, :method => :put, :html => { :class => 'form-vertical' }) do |f| %>

暫無
暫無

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

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