Lechucico
Lechucico

Reputation: 2112

ruby on rails relationship not working

I'm trying to access all relations beetween two models: Serie has multiple categories and multiple categories can be in diferent series. Is a many to many relationship.

I try to do the following:

class SeriesController < ApplicationController

   def category
      @category = params[:category]
      @series = []

      Serie.all.each do |serie|
         @serie.categories.all.each do |cat|
            if @cat.category == @category
               @series << @serie
            end
         end
      end
   end

end

Rails throws me that exception:

undefined method `categories' for nil:NilClass

Here are the models:

class Serie < ApplicationRecord
  has_many :types
  has_many :categories, through: :types
end

class Type < ApplicationRecord
  belongs_to :serie
  belongs_to :category
end

class Category < ApplicationRecord
  has_many :types
  has_many :series, through: :types
end

class CreateCategories < ActiveRecord::Migration[5.1]
  def change
     create_table :categories do |t|
      t.string :category
      t.timestamps
    end
  end
end

class CreateTypes < ActiveRecord::Migration[5.1]
  def change
    create_table :types do |t|
      t.references :serie, index: true
      t.references :category, index: true
      t.timestamps
    end
  end
end

I don't know why this doesn't work.

Any idea? Thanks.

Upvotes: 1

Views: 180

Answers (2)

Rockwell Rice
Rockwell Rice

Reputation: 3002

You are mixing up your variables in your create method. You reference @serie which is set to equal [] so in the each it is empty, the variable you create there is serie so use that.

....
      Serie.all.each do |serie|
      serie.categories.all.each do |cat|
        if cat.category == @category
           @series << serie
        end
     end
  end

Upvotes: 1

spickermann
spickermann

Reputation: 107117

Change

Serie.all.each do |serie|
  @serie.categories.all.each do |cat|
     if @cat.category == @category
       @series << @serie
     end
     # ...

to

Serie.all.each do |serie|
  serie.categories.all.each do |cat|
     if cat.category == @category
       @series << serie
     end
     # ...

because there a local variables serie and cat defined in the blocks, but no instance variables @serie or @cat

Upvotes: 3

Related Questions