Lechucico Lechucico -4 years ago 89
Ruby Question

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.

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download