Rails 3: undefined method messages for Folder

≡放荡痞女 提交于 2019-12-25 08:04:23

问题


I'm running Rails 3 and like to have a message system. Here is the tutorial for it: http://www.novawave.net/public/rails_messaging_tutorial.html

It's for Rails 2 so I was trying to implement it in Rails 3.

Everything went fine and i can send messages. But when i like to check my inbox this error shows up:

undefined method `messages' for #<Folder:0x0000010419fd48>

Mailbox Controller:

class MailboxController < ApplicationController
  def index
    redirect_to new_session_path and return unless logged_in?
    @folder = current_user.inbox
    show
    render :action => "show"
  end

  def show
    @folder ||= current_user.folders.find(params[:id])
    @messages = @folder.messages.paginate :per_page => 10, :page => params[:page], :include => :message, :order => "messages.created_at DESC"
  end
end

When I check the console with:

User.find(9).inbox

everything is fine and the output is:

ruby-1.9.2-p180 :085 > User.find(9).inbox
 => #<Folder id: 1, user_id: 9, parent_id: nil, name: "Inbox", created_at: "2011-04-27 21:37:00", updated_at: "2011-04-27 21:37:00"> 

But when I add .messages it returns the error.

When i try to fetch the messages manual it's working:

User.find(9).received_messages
 => [#<MessageCopy id: 7, recipient_id: 9, message_id: 8, folder_id: 1, created_at: nil, updated_at: "2011-04-27 23:15:25">, #<MessageCopy id: 8, recipient_id: 9, message_id: 9, folder_id: 1, created_at: nil, updated_at: "2011-04-27 23:25:06">]

The Models & Controllers are the same as in the tutorial.

Any ideas?

Greets

EDIT:

*Added the Error and the View

Error:

undefined method `messages' for #<Folder:0x0000010409c900>

app/controllers/mailbox_controller.rb:11:in `show'
app/controllers/mailbox_controller.rb:5:in `index'

Mailbox/show view:

<h2><%=h @folder.name %></h2>

<table border="1">
  <tr>
    <th>From</th>
    <th>Subject</th>
    <th>Received</th>
  </tr>

  <% @messages.each do |message| %>
    <tr>
      <td><%=h message.author.login %></td>
      <td><%= link_to h(message.subject), message_path(message) %></td>
      <td><%= distance_of_time_in_words(message.created_at, Time.now) %> ago</td>
    </tr>
  <% end %>
</table>

<%= will_paginate @messages %>

回答1:


You may have missed a step in establishing the relationships in your models.

Check that your Folder.rb (folder model) has a has_many relationship established with messages.

class Folder < ActiveRecord::Base
   has_many :messages, :class_name => "MessageCopy"

The error you are getting in the controller is telling you that this is not the case, the folder model has no method called 'messages', which ActiceRecord (Rails' ORM) will generate for you with the has_many code.

ian.



来源:https://stackoverflow.com/questions/5812027/rails-3-undefined-method-messages-for-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!