我有这些模型,但是当我执行Message.last.people或Message.last.recipient_lists时,我收到错误。如何引用收件人列表或附加到有活动记录的邮件的人?我需要做RecipientList.where(:message => Message.last)
吗?似乎应该有更好的方法通过.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
我收到此错误
Message.last.recipient_lists
消息加载(0.7ms)SELECT &#34;消息&#34;。* FROM&#34;消息&#34;订购消息&#34;消息&#34;。&#34; id&#34; DESC限制1 NoMethodError:未定义的方法`recipient_lists&#39;对来自/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&#39;来自(irb):1来自 /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/railties-4.0.9/lib/rails/commands/console.rb:90:instart' from /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/railties-4.0.9/lib/rails/commands/console.rb:9:in
开始&#39;从 /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:in
需要&#39;来自bin / rails:4:in `&#39;Message.last.people消息加载(1.0ms)SELECT&#34;消息&#34;。* FROM &#34;消息&#34;订购消息&#34;消息&#34;。&#34; id&#34; DESC限制1 ActiveRecord :: HasManyThroughAssociationNotFoundError:找不到 关联:模型消息中的recipient_list
答案 0 :(得分:1)
您需要在Message和Person中明确包含has_many :recipient_lists
,并在:recipient_lists
选项中正确复制through:
,如下所示:
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