Search code examples
ruby-on-rails-5has-and-belongs-to-many

rails 5 belongs_to or has_and_belongs_to_many?


I've been out of the loop for a while and humbly request a refresher.

I would like to list all Partners under their respective PartnerCategories in an accordion style toggle

      <div class="panel-group">
        <% @categories.each do |category| %>
          <div class="panel panel-default">
            <div class="panel-heading">
              <h4 class="panel-title">
                <a class="accordion-toggle" data-toggle="collapse" data-parent="#accordion" href="#collapseOne">
                  <%= category.name %>
                </a>
              </h4>
            </div>
            <div id="collapseOne" class="panel-collapse collapse in">
              <div class="panel-body">
                <% category.partners.each do |partner| %>
                  <p style="text-align:left;"><%= link_to "#{partner.firma}".html_safe, partner_path(partner) %><span style="float:right;"><%= "#{partner.full_street_address}"%></span></p>
                <% end %>
              </div>
            </div>
          </div>
        <% end %>
      </div>

Models:

class Partner
  has_many :partner_categories, :dependent => :destroy, :inverse_of => :partner
  accepts_nested_attributes_for :partner_categories, :allow_destroy => true


class PartnerCategory
  belongs_to :partner, :inverse_of => :partner_categories

Controller:

class PartnersController < ApplicationController
  def index
    @partners = Partner.all
    @categories = PartnerCategory.all
  end

When I do this I get a no method error on

category.parters.each

I know I'm missing something.. just can't find the solution.

Please be gentle.. I know this is basic for most.. and thanks in advance!


Solution

  • Your PartnerCategory model has a belongs_to relationship to your Partner model, which means that your category only has partner instead of partners per record.

    To achieve what you want, I would suggest you to generate another model with a setup similar to the below, this is especially useful when you need to add validations or callbacks join model.

    class Partner
      has_many :partner_categories
      has_many :categories, through: :partner_categories
    end
    
    class PartnerCategory
      belongs_to :partner
      belongs_to :category
    end
    
    class Category
      has_many: partner_categories
      has_many :partners, through: :partner_categories
    end
    

    This way you will have a has_many relationships through the PartnerCategory and you will have access to all partners of a category in your category.parters.each