corroded
corroded

Reputation: 21564

has many through problem

I have a has many through relationship with my groups and guests models. Here are the models:

class Group < ActiveRecord::Base  
  has_many :memberships, :dependent => :destroy
  has_many :guests, :through => :memberships

  def self.find(group)
    self.find_by_name(group).guest.collect{ |x| x.name  }
  end
end

class Guest < ActiveRecord::Base
  has_many :memberships, :dependent => :destroy
  has_many :groups, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :guest
  belongs_to :group
end

I am checking in console and here are the results:

ruby-1.9.2-head :001 > Group.first.guests
=> [] 

ruby-1.9.2-head :002 > Guest.first.groups
(Object doesn't support #inspect)
=> 

Why doesn't the second one work? I tried inspecting the class of groups but it always returns an error:

ruby-1.9.2-head :005 > Guest.first.groups.class
NoMethodError: undefined method `guest' for nil:NilClass

Can anyone help me with this? I am actually just trying to follow this guide: http://millarian.com/programming/ruby-on-rails/quick-tip-has_many-through-checkboxes/

Upvotes: 0

Views: 725

Answers (2)

Peter Brown
Peter Brown

Reputation: 51697

Your find class method is using guest instead of guests:

self.find_by_name(group).guest.collect{ |x| x.name  }

I also noticed that you are overriding a built in ActiveRecord method, find, which is not recommended.

Upvotes: 1

Shreyas
Shreyas

Reputation: 8757

This is happening because Guest.first is returning nil. create a guest object and try it out.

Upvotes: 0

Related Questions