1

我在 Gumtree.com 之类的网站上工作,用户在其中创建帖子,突出他们的各种需求(例如,我在第 X 天需要一名摄影师)。

消息功能有一些问题。我正在使用简单的私人消息传递插件。

问题出在用户填写发送消息/回复帖子的表单中。当我尝试访问 /messages/new 时出现以下错误:

ActiveRecord::RecordNotFound in MessagesController#new
Couldn't find User without an ID

在下面附上我的模型-感谢您的任何建议!

谢谢,

费萨尔

消息控制器

class MessagesController < ApplicationController

before_filter :set_user

def index
if params[:mailbox] == "sent"
  @messages = @user.sent_messages
else
  @messages = @user.received_messages
end
end

def show
@message = Message.read_message(params[:id], current_user)
end

def new
@message = Message.new

if params[:reply_to]
  @reply_to = @user.received_messages.find(params[:reply_to])
  unless @reply_to.nil?
    @message.to = @reply_to.sender.login
    @message.subject = "Re: #{@reply_to.subject}"
    @message.body = "\n\n*Original message*\n\n #{@reply_to.body}"
  end
end
end

def create
@message = Message.new(params[:message])
@message.sender = @user
@message.recipient = User.find_by_login(params[:message][:to])

if @message.save
  flash[:notice] = "Message sent"
  redirect_to user_messages_path(@user)
else
  render :action => :new
end
end

def delete_selected
if request.post?
  if params[:delete]
    params[:delete].each { |id|
      @message = Message.find(:first, :conditions => ["messages.id = ? AND (sender_id = ? OR recipient_id = ?)", id, @user, @user])
      @message.mark_deleted(@user) unless @message.nil?
    }
    flash[:notice] = "Messages deleted"
  end
  redirect_to :back
end
end

private
def set_user
  @user = User.find(params[:user_id])
end
end

消息模型

class Message < ActiveRecord::Base

is_private_message

attr_accessor :to

end

用户模型

class User < ActiveRecord::Base

has_many :posts  
has_one :profile
has_private_messages

attr_accessible :email

validates_presence_of :email
validates_uniqueness_of :email, :message =>"Hmm, that email's already taken"
validates_format_of :email, :with => /^([^\s]+)((?:[-a-z0-9]\.)[a-z]{2,})$/i, :message => "Hi! Please use a valid email"


end

消息>新视图

<% form_for @message, :url => user_messages_path(@user) do |f| %>
<p>
To:<br />
    <%= f.text_field :to %>
    <%= error_message_on @message, :to %>
</p>
<p>
Subject:<br />
<%= f.text_field :subject %>
<%= error_message_on @message, :subject %>
</p>
<p>
  Message<br />
  <%= f.text_area :body %>
        <%= error_message_on @message, :body %>
</p>
<p>
  <%= submit_tag "Send" %>
</p>
<% end %>
4

1 回答 1

2

您确定您的新消息页面会收到:user_idparams?即使这是真的,我怀疑这是您的意图,因为任何人都可以通过传递另一个用户来假装是另一个用户:user_id

所以你在底部的行:

@user = User.find(params[:user_id]) # I think it's the cause of your error -- no :user_id is passed

似乎必须是:

@user = User.find(session[:user_id])

我想你听说过会话。

于 2012-04-18T20:21:26.370 回答