There is the rails convention "Skinny Controllers Fat Models" and i tried to follow it, In my controller i had so far:
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
....
So now i tried to move some of this code into my model( i tried several things but here is one try:)
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
And then i get the error:
undefined method `username' for nil:NilClass
So what did i wrong thanks?