Alina
Alina

Reputation: 2261

Ruby on Rails, call a function from model in a controller

I have the following method in my controller:

def create
  p_attr=params[:upload]
  p_attr[:upload] = params[:upload][:upload].first if params[:upload][:arraydb].class == Array
  @upload = Upload.new(p_attr)

  respond_to do |format|
    if @upload.save
      @arraydb.process_name
    end
  end 
end

in a model I have another method where I can process the upload that was just saved:

def self.process_name 
  update_attributes(:user_id => current_user.id)
  update_attributes(:defined => "no")
end

It gives me an error that the method process_name is not defined for Upload

What is the problem and how can I update the attributes of just saved file in a model from a controller? Thanks in advance.

Upvotes: 1

Views: 6241

Answers (2)

Cezar
Cezar

Reputation: 56332

In Ruby, methods defined with self. before the name are class methods. This means you can only call such methods on the class itself, not on its instances.

This means that:

upload = Upload.new()
upload.process_name

results in an error

While:

Upload.process_name

will call the method.

Since what you really want to do is to call process_name in instances of the Upload class, you can correct your code by removing self. from your method definition, resulting in:

def process_name
    update_attributes(:user_id => current_user.id)
    update_attributes(:defined => "no")
end

Upvotes: 7

Dave Newton
Dave Newton

Reputation: 160191

It isn't-it's defined for the class, not instances.

You're trying to call it on an instance. Make it an instance method.

Upvotes: 2

Related Questions