开发者

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, :depend开发者_C百科ent => :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/


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜