我正在尝试在 Rails 中实现一个私人消息系统,这是我的表:
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
这是我的message
模型:
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 %>
和控制器:
def create
@message = Message.new(params[:message])
@message.sender_id = current_user
if @message.save
set_flash "Message sent"
render 'index'
else
set_flash "Message Failed"
render 'index'
end
结尾
这个想法是用户 1在文本字段中输入user2电子邮件,recipient_id
然后之前的验证将触发并根据他的电子邮件检索用户 2user table
id,但是当我尝试它时,我收到此错误:
undefined method `to_i' for #<User:0x00000004344780>
问题是什么?
编辑:
这是引发错误的行:
@message.sender_id = current_user
如果我改变current_user
它current_user.id
thorws这个错误:
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
谢谢