Dan Brookwell
Dan Brookwell

Reputation: 341

Referencing multiple models in Rails

I have departments with many positions with many crewmembers. I am trying to make a page of a master list of crewmembers, grouped by their positions which are grouped by their departments. I know the code below is wrong, but hopefully someone could point me in the correct direction.

<% @departments.each do |dept| %>
    <% if Department.position.include? crewmember %>
      <%= dept.department %><br />
      <% @positions.each do |pos| %>
        <% if Position.crewmember.any? %>
          <%= pos.position %><br />
          <%= pos.position.crewmember %>
        <% end %>
      <% end %>
    <% end %>
  <% end %>

EDIT- My models:

class Crewmember < ActiveRecord::Base
    belongs_to :production
    belongs_to :callsheet

    validates :firstname, :email, presence: true

    scope :visible, where(visible: true)

    def name
        "#{firstname} #{lastname}"
    end

end

class Department < ActiveRecord::Base
    has_many :positions
    belongs_to :production

    attr_accessible :department
    validates :department, presence: true
end

class Position < ActiveRecord::Base
    belongs_to :department

    attr_accessible :department_id, :position, :department

end

Upvotes: 0

Views: 37

Answers (1)

Gokul
Gokul

Reputation: 3231

Your question is not clear. But, as I understood I think this is what you need:

<% @departments.each do |dept| %>
      <%= dept.name %><br />
      <% dept.positions.each do |pos| %>
          <%= pos.name %><br />
          <% pos.crewmembers.each do |cm| %>
             <%= cm.name %><br />
          <% end %>
      <% end %>
<% end %>

Upvotes: 0

Related Questions