rails 4 many to many association with value

89 Views Asked by At

i would like to learn how can'i make many to many association with rails.

i have three models: Poject(id, name,...), cheklist(id,name), fields(id,name,id_checklist) the relation between checklist and field work fine.

every checklists have many fields, so each field belong to checklist. my problem, is that i don't know how to show for every project, the list of checklist with their child's.

i would like to have a div with something like that:

Checklists:

  1. Project Manager
    • signed contract : checked? Yes or no
    • server hosting information : checked? Yes or no
    • submit button for project manager
  2. Developer
    • create dev environment : checked? Yes or no
    • ....
    • submit button for developer

checked? Yes or no will be two radio button.

Super user can manage checklists (create, update...) and fields of each checklist.

So when I will create project, I will have a div showing all checklists with nested fields (default value is false) . User will be able to update every checklist from project homepage. can someone help me please.

thanks.

1

There are 1 best solutions below

5
On

If every project has the same n checklists, each of which has the same fields, why create an abstract checklist and fields relation at all?

Instead, consider using more concrete definitions:

# project.rb
class Project < ActiveRecord::Base
  has_one :developer_checklist
  has_one :project_manager_checklist
end

# developer_checklist.rb
class DeveloperChecklist < ActiveRecord::Base
  belongs_to :project, inverse_of: :developer_checklist
  # has properties: name (string), create_dev_env (bool), etc.
end

# project_manager_checklist.rb
class ProjectManagerChecklist < ActiveRecord::Base
  belongs_to :project, inverse_of: :project_manager_checklist
  # has properties: name (string), server_hosting_info (bool), etc.
end

Now you don't have to have any demeter-crazy loops to create your views, it's just a matter of creating an update form for each of your concrete checklist types.

<%= form_for developer_checklist do |f| %>
...
<% end %>
<%= form_for project_manager_checklist do |f| %>
...
<% end %>

From that starting point, you could create some classical inheritance between the checklists if you like that sort of thing.

This wouldn't work if you allow users to define custom checklists, but there's no indication of that requirement in the original question.