0
votes

I have these models, but when I do a Message.last.people or Message.last.recipient_lists I get an error. How would I reference the Recipient Lists or people attached to a message with active record? Would I need to do a RecipientList.where(:message => Message.last) ? Seems like there should be a better way to do it through the .message ?

class Message < ActiveRecord::Base
    has_many   :people, through: :recipient_list
end

class Person < ActiveRecord::Base
  has_many :messages, through: :recipient_list
end

class RecipientList < ActiveRecord::Base
    belongs_to :person
    belongs_to :message
end

I get this error

Message.last.recipient_lists
Message Load (0.7ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."id" DESC LIMIT 1 NoMethodError: undefined method `recipient_lists' for

from /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/activemodel-4.0.9/lib/active_model/attribute_methods.rb:439:in

method_missing' from /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/activerecord-4.0.9/lib/active_record/attribute_methods.rb:168:in method_missing' from (irb):1 from /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/railties-4.0.9/lib/rails/commands/console.rb:90:in start' from /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/railties-4.0.9/lib/rails/commands/console.rb:9:in start' from /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/railties-4.0.9/lib/rails/commands.rb:62:in <top (required)>' from bin/rails:4:inrequire' from bin/rails:4:in `'

Message.last.people Message Load (1.0ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."id" DESC LIMIT 1 ActiveRecord::HasManyThroughAssociationNotFoundError: Could not find the association :recipient_list in model Message

1
You fail to state the error. Is it something about a nil perchance?David Hoelzer
@DavidHoelzer edited with error messages for the queries Message.last.recipient_lists and Message.last.peopleparameter
Did you run the migrations?David Hoelzer

1 Answers

2
votes

You need to explicitly include has_many :recipient_lists in both Message and Person, and also correctly pluralize :recipient_lists in the through: option, like so:

class Message < ActiveRecord::Base
  has_many :recipient_lists
  has_many :people, through: :recipient_lists
end

class Person < ActiveRecord::Base
  has_many :recipient_lists
  has_many :messages, through: :recipient_lists
end

class RecipientList < ActiveRecord::Base
  belongs_to :person
  belongs_to :message
end