Question

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?

Was it helpful?

Solution

You can easily move your code from controller to model like that:

#controller
def create
  Message.create_with_sender(message_params, @current_user)
end

#model 
class Message < ActiveRecord::Base

  def self.create_with_sender(params, user)
    message = new(params)
    message.sender_username = user.username
    message.sender_model = user.class.to_s
    message.sender_id = user.id
    if message.sender_model == "Department"
       user.update_column(:gelesen, user.employees.map { |s| "#{s.username}" }.join(','))
    else
      user.update_column(:gelesen, message.recipient_username)
    end
    message.save
  end

end

OTHER TIPS

Are you sure that you're setting @current_user to anything? @current_user is usually set when used in conjunction with a user management gem such as Devise. Provided you have a session started, the function usually works something like:

def current_user
  @current_user ||= User.find(session[:user_id])
end

Either way, the issue is that @current_user is not being set anywhere.

Secondly, I'm not sure you're using update_column correctly. That's mainly used for updating tables on the database. It's more likely that you want to use something like #update_attributes (http://apidock.com/rails/ActiveResource/Base/update_attributes).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top