Rails Uninitialized控制器中的常量

时间:2014-05-18 10:47:25

标签: ruby-on-rails ruby activerecord ruby-on-rails-4

这是ActiveRecord having 2 FKs from the same column in a table的后续问题我收到消息'未初始化的常量User :: Message',我不知道是什么导致它。

我的消息控制器的创建操作是

def create
@message = current_user.packages.build(message_params)
@message.sender = current_user
@message.receiver = User.find(params[:id])
@message.date = Time.now
if @message.save
  flash[:success] = "Message Created!"
else
  flash[:danger] = "Message Not Created!"
end

 redirect_to user_path
end

我将控制器添加到routes.rb文件

resources :messages, only: [:create, :destroy]

我的用户控制器的操作是

def show
@user = User.find(params[:id])

@message = @user.messages.build #error is thrown here

@package_feed_items = @user.packages.paginate(page: params[:page],:per_page => 5)
@route_feed_items = @user.routes.paginate(page: params[:page],:per_page => 5)
end

表单位于views目录的'messages'文件夹中。这是从我的用户控制器中使用

的视图调用的
<%= render 'messages/create_message_modal' %>

我的消息模型现在是

class Message < ActiveRecord::Base
  belongs_to :sender, class_name => :user, foreign_key => 'sender_id'
  belongs_to :receiver, class_name => :user, foreign_key => 'receiver_id'

  default_scope -> { order('created_at DESC') }

  validates :receiver_id, presence: true
  validates :sender_id, presence: true
  validates :body, presence: true
  validates :date, presence: true

  state_machine :initial => :unOpened do
   state :unOpened, value: "Un-Opened"
   state :opened, value: "Opened"
   state :deleted, value: "Deleted"

   event :open do
     transition :unOpened => :opened
   end

   event :delete do
     transition :opened => :deleted
   end
 end
end

我的用户模型是

class User < ActiveRecord::Base
    ... other relations ... 
    has_many :messages
    ... validation & state machine ...
end

EDIT 我的日志文件的尾部

Completed 500 Internal Server Error in 8ms

NameError (uninitialized constant User::Message):app/controllers/users_controller.rb:33:in `show'


  Rendered /Users/jeff/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.4ms)
  Rendered /Users/jeff/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms)
  Rendered /Users/jeff/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.8ms)
  Rendered /Users/jeff/.rvm/gems/ruby-2.0.0-p247/gems/actionpack-4.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (11.2ms)

1 个答案:

答案 0 :(得分:0)

为用户模型指定class_name选项,如下所示

class User < ActiveRecord::Base
  has_many :messages, class_name: 'Message'
end

试试这个应该有用,无论如何你需要找到为什么直接关系不起作用。