0

我想要做以下事情:事件既可以讓個別學生參與競爭,也可以讓學生團隊參與。所以我把它多態,如下:如何資源管理與關聯模型的多態關聯?

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;博士:我怎樣使用這些資源型控制器的工作?

我已經有一個事件控制器,它允許我刪除它的屬性。我有一個學生管理員也是這樣做的。所以現在我需要競爭對手控制器來組合它們。在那裏,我畫了一個空白。

我想要的是能夠在一個屏幕上選擇一個事件競爭對手 - 從學生複選框列表中。如果我創建像

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

嵌套路線然後我就可以去events/1/competitors顯示競爭對手的名單。但是,那麼它應該顯示團隊還是學生?我不想讓它變成一團糟。那麼我應該爲這兩個人分別設置控制器嗎?他們將如何命名?我將如何與他們互動?

比方說,我做的做一個控制器專爲學生的競爭對手:

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_forsimple_form_for(@event, @competitors)並將其構建的路徑更新行動。

基本上,我不知道如何最好地去做這一切。我是否過於嚴格,堅持資源?感謝您的幫助。

回答

0

我用一個單一的資源:

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| %>