Many-to-many checkbox in Ruby on Rails

My Ruby on Rails application has a DocumentType model and a PersonType model. A document is of type DocumentType (e.g., Letter, Postcard) and lists one or more people. Each person is assigned a PersonType type to represent their relationship to the Document (sender, recipient, author, etc.). The user is allowed to assign people only for PersonType types related to DocumentType.

Table Definitions:

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

Model Definitions:

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

Examples of tables:

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

When the user adds Person to the document, they will choose what relation this Person refers to the document, and which will be stored in the Person model (or extended model).

PersonTypes, DocumentType (, , ).

, ... , , - DocumentTypes, document_types_person_types, PersonTypes, , PersonType:

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

PersonTypes PersonTypes, Person . , , . - - ?

: , ,

<% 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 %>
+5
1

DocumentType person_type_ids, .

, , document_type[person_type_ids][] , , , , ,

document_type.update_attributes params[:document_type]

. , , ( ), . , , 0 ( , id), 0 .

+2

All Articles