2013-03-16 38 views
5

我的Ruby on Rails應用程序有一個DocumentType模型和一個PersonType模型。文檔屬於DocumentType(例如Letter,Postcard),並列出一個或多個人。每個人被分配一個PersonType來表示他們與文檔(發件人,收件人,作者等)的關係。只允許用戶將人員分配給與DocumentType相關的PersonType。基於多對多關係的Ruby on Rails中的複選框表單

表定義:

create_table "document_types", :force => true do |t| 
t.string "name" 
end 

create_table "document_types_person_types", :id => false, :force => true do |t| 
t.integer "document_type_id" 
t.integer "person_type_id" 
end 

create_table "person_types", :force => true do |t| 
t.string "name" 
end 

模型定義:

class Document < ActiveRecord::Base 
has_many :people, :dependent => :destroy 
belongs_to :document_type 
end 

class DocumentType < ActiveRecord::Base 
has_many :documents 
has_and_belongs_to_many :person_types 
end 

class Person < ActiveRecord::Base 
belongs_to :document 
has_and_belongs_to_many :person_types 
end 

class PersonType < ActiveRecord::Base 
has_and_belongs_to_many :people 
has_and_belongs_to_many :document_types 
end 

表的例子:

documents 
id: 1 
document_type_id: 1 
name: Letter from John Smith to Jane and Joe Smith 

document_types 
id: 1 | name: letter 

document_types_person_types 
document_type_id: 1 | person_type_id: 1 
document_type_id: 1 | person_type_id: 2 
document_type_id: 1 | person_type_id: 4 

person_types 
id: 1 | name: Sender 
id: 2 | name: Recipient 
id: 3 | name: Photographer 
id: 4 | name: Author 

people 
id: 1 | document_id: 1 | name: John Smith | person_type_id: 1 
id: 2 | document_id: 1 | name: Jane Smith | person_type_id: 2 
id: 3 | document_id: 1 | name: Joe Smith | person_type_id: 2 

當用戶添加一個人到一個文檔,他們將選擇什麼樣的人與文檔的關係,並將存儲在人員模型(或擴展模塊)中EL)。

文檔只會顯示與該DocumentType相關的PersonType(例如,照片不會有作者,但會有攝影師)。

所以在這一切之後...我想實現的是一個管理接口,爲DocumentTypes,代表document_types_person_types表給出了所有PersonTypes並讓我選擇一個複選框,如果一個PersonType適用:

EDIT DocumentType Letter 
Sender  [x] 
Recipient [x] 
Photographer [ ] 
Author  [x] 

那些被選中的人物類型將成爲將人物添加到文檔時唯一可用的人物類型。希望比我在解釋中的誇大嘗試可能會更直接。任何人都可以提供任何指針?

編輯: 以供將來參考,基於以下弗雷德裏克的答案,這個工作

<% for pt in PersonType.find(:all) %> 
    <%= check_box_tag "document_type[person_type_ids][]", pt.id, @document_type.person_types.include?(pt) %> 
    <%= pt.name %> 
<% end %> 

回答

2

有了這樣的一個協會,DocumentType將有person_type_ids方法返回關聯的ID數組人類類型。

因此,如果您創建一組複選框,其中名稱爲document_type[person_type_ids][],其價值是每個人,然後鍵入的內容將被提交是包含受檢查的人類型ID陣列的ID,所以

document_type.update_attributes params[:document_type] 

會更新關聯。這裏唯一的微妙之處在於,如果沒有選中複選框,則不會提交數組(您不能提交空數組),並且關聯的人員類型列表不會被清除。我通常通過隱藏字段來解決這個問題,該字段將數值0添加到數組中(因爲我知道這永遠不會是合法的ID),然後從控制器中的數組中去掉0。

+0

非常感謝Frederick快速而有用的回答。我會放棄並報告。 – 2013-03-16 17:53:03

+0

D'oh,編輯了答案而不是我的問題,但是有效的是以上。 – 2013-03-16 19:43:38

+0

嗨,我試過了,但我得到這個錯誤'不能大規模分配受保護的屬性:'。你有什麼建議嗎?謝謝 – Teo 2013-06-15 07:38:49