Ruby on rails 验证前的Rails抛出错误

Ruby on rails 验证前的Rails抛出错误,ruby-on-rails,validation,Ruby On Rails,Validation,我正在尝试在rails中实现一个pivate消息系统,这是我的表: create_table :messages do |t| t.integer :sender_id, :null => false t.integer :recipient_id, :null => false t.text :content t.boolean :read, :null => false,

我正在尝试在rails中实现一个pivate消息系统,这是我的表:

create_table :messages do |t|
  t.integer    :sender_id,          :null => false
  t.integer    :recipient_id,       :null => false
  t.text       :content
  t.boolean    :read,               :null => false, :default => false

  t.timestamps
end
这是我的
信息
模型:

  attr_accessible :recipient_id, :sender_id, :content

  belongs_to :user

  validates_presence_of :recipient_id, :sender_id, :content

  before_validation :recipient

  def recipient
    self.recipient_id = User.find_by_email(self.recipient_id.to_s).id
  end
我的表格:

<%= form_for @message, :url => {:action => 'index'}, :as => :message do |message| %>
  <%= message.text_field :recipient_id, :placeholder => "to" %>

  <%= message.text_area :content, :placeholder => "i am saying..."%>

  <%= message.submit "Send" %>
<% end %>
结束

其想法是,用户1在
收件人id
文本字段中输入user2电子邮件,然后在生效之前,将根据其电子邮件从
用户表
中触发并重新获取用户2 id,但当我尝试时,会出现以下错误:

undefined method `to_i' for #<User:0x00000004344780>
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
如果我将
current_user
更改为
current_user.id
则会出现此错误:

undefined method `to_i' for #<User:0x00000004344780>
Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id
在这一行:

    self.recipient_id = User.find_by_email(self.recipient_id.to_s).id

谢谢

在create方法中尝试一下

@message.sender_id = current_user.id
而不是此
@message.sender\u id=当前用户

我认为您正在使用
当前用户
对象设置
sender\u id
,而该对象需要一个
id
整数

编辑:

对于新错误,
User.find\u by\u email
方法无法找到记录,因此返回
nil

你的代码也有问题

self.recipient_id = User.find_by_email(self.recipient_id.to_s).id
您正在设置
self.recipient\u id
并使用
self.recipient\u id
进行搜索
self.recipient\u id
似乎是
nil
,除非在其他地方设置了
self.recipient\u id


如果数据库中有与
self.recipient\u id
匹配的收件人,则此代码不会执行任何操作。它将
self.recipient\u id
设置为
self.recipient\u id

现在我得到了一个名为id for nil的错误
,它将被错误地设置为4——如果您确实想要nil的id,请使用object\u id
您应该将stacktrace指向引发错误的文件和代码行。请添加此信息。@iltempo-问题已更新。