【问题标题】:rails 4 has many through association queryrails 4 有很多通过关联查询
【发布时间】:2015-07-23 00:20:20
【问题描述】:

我有这些模型,但是当我执行 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) 选择 "messages".* FROM "messages" ORDER BY "messages"."id" DESC LIMIT 1 NoMethodError: 未定义的方法 `recipient_lists' 用于

来自 /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' 来自 (irb):1 来自 /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' 来自 /home/nick/.rvm/gems/ruby-2.0.0-p598/gems/railties-4.0.9/lib/rails/commands.rb:62:in &lt;top (required)&gt;' from bin/rails:4:inrequire' 来自 bin/rails:4:in `'

Message.last.people 消息加载 (1.0ms) SELECT "messages".* FROM "messages" ORDER BY "messages"."id" DESC LIMIT 1 ActiveRecord::HasManyThroughAssociationNotFoundError: 找不到 关联 :recipient_list in model Message

【问题讨论】:

  • 您没有说明错误。是关于nil 的机会吗?
  • @DavidHoelzer 编辑了查询 Message.last.recipient_lists 和 Message.last.people 的错误消息
  • 你运行迁移了吗?

标签: ruby-on-rails activerecord has-many-through


【解决方案1】:

您需要在 Message 和 Person 中明确包含 has_many :recipient_lists,并在 through: 选项中正确复数 :recipient_lists,如下所示:

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

【讨论】:

    猜你喜欢
    • 2018-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    相关资源
    最近更新 更多