有rails约定“Skinny Controllers Fat Models”,我试图遵循它,在我的控制器中我到目前为止:
def create
@message = Message.new(message_params)
@message.sender_username = @current_user.username
@message.sender_model = @current_user.class.to_s
@message.sender_id = @current_user.id
if @message.sender_model == "Department"
@current_user.update_column(:gelesen, @current_user.employees.map { |s| "#{s.username}" }.join(','))
else
@current_user.update_column(:gelesen, @message.recipient_username)
end
....
所以现在我尝试将其中一些代码移动到我的模型中(我尝试了几件事,但这里是一个尝试:)
class Message < ActiveRecord::Base
before_save :set_sender, :add_gelesen
def set_sender
sender_username = @current_user.username
sender_model = @current_user.class.to_s
sender_id = @current_user.id
end
def add_gelesen
if @message.sender_model == "Department"
@current_user.update_column(:gelesen, @current_user.employees.map { |s| "#{s.username}" }.join(','))
else
@current_user.update_column(:gelesen, @message.recipient_username)
end
end
end
然后我得到错误:
undefined method `username' for nil:NilClass
那我做错了什么谢谢?