Rails 4.0 - NameError未初始化的内容 - 与非常规外键的has_many关系

时间:2013-10-12 21:10:06

标签: ruby-on-rails

我有下表,我正在尝试在用户之间存储消息。我已经尽我所能设置了关系,但我得到的是NameError in Messages#index uninitialized constant Member::messages

消息表的数据库模式

create_table "messages", force: true do |t|
  t.datetime "created_at"
  t.datetime "updated_at"
  t.text     "message",    null: false
  t.boolean  "read",       null: false
  t.integer  "from_id",    null: false
  t.integer  "to_id",      null: false
end

会员模特

class Member < ActiveRecord::Base
  has_many :received_messages, :class_name => :messages, :foreign_key => "to_id"
end

消息模型

class Message < ActiveRecord::Base
  belongs_to :member
end

带有辅助方法的ApplicationController

class ApplicationController < ActionController::Base

  helper_method :unread_messages

  def unread_messages
    @unread_messages ||= current_user.received_messages.where(:unread => true) unless current_user.received_messages.nil?
  end
end

我在aplication.html.erb布局模板

中的此语句中收到错误

<span class="badge"><%= unread_messages.count %></span>

可能导致此问题的原因。这是一个非常通用的错误,通常意味着我忘记设置关联,但这种关联是不同的,我没有必要在超出默认命名约定之前做一个...思考?

1 个答案:

答案 0 :(得分:1)

:class_name密钥应为“消息”。