AlexNikolaev94
AlexNikolaev94

Reputation: 1209

Can't figure out relationships between two models

I'm writing a CMS plugin, in which I have two basic models -- Category and Entry. Each of this model is related to another through has_and_belongs_to_many relationship. But I can't figure out, how should I point this out in their controllers and routes. For example, I need to render all of entries belongning to certain category, within categories#show action. Here are the models:

class Entry < ApplicationRecord
  has_and_belongs_to_many :categories
end

class Category < ApplicationRecord
  has_and_belongs_to_many :entries
end

This is my categories_controller:

def show
  @category = Category.find(params[:id])
  @entries = @category.entries.all
end

and within my show.html.erb template:

<% @entries.each do |entry| %>
  <%= link_to entry.title, entry_path(entry) %>
<% end %>

and my routes:

resources :categories do
  scope '/:content_class' do
    resources :entries
  end
end

But every time I get an error, that there's no categories_entries relationship in the database. What am I doing wrong?

Here is a link to the whole project

Upvotes: 1

Views: 84

Answers (2)

Kokozaurus
Kokozaurus

Reputation: 639

After I looked at the github repository you provided, I think you need to have a cross-reference table to make the association work.

The reason for this is that there should be a way to distinguish which records of one table have connection with which of the other table. In the case of one-to-many relationship like has_one or belongs_to this is achieved by recording the id of one of the models in the table of the other model. Since you need more than one id recorded in each of the records in both tables, this is only possible with a separate table.

Try making such a table with only two fields: category_id and entry_id, with a migration similar to this snippet:

class CreateCategoryEntryJoinTable < ActiveRecord::Migration
  def change
    create_table :categories_entries, id: false do |t|
      t.integer :category_id
      t.integer :entry_id
    end
  end
end

You could read more from here: http://apidock.com/rails/v4.2.1/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many

Upvotes: 1

Bart Jedrocha
Bart Jedrocha

Reputation: 11570

A has_and_belongs_to_many association requires a join-table which you haven't created. Please see this guide for more information.

Upvotes: 0

Related Questions