1

User is required to input a name (that will insert into database) and I need the user input name to use in another function to process then I need the newly processed input to insert into database.

So far, i manage to do is:

 A name inserted into database
 -> I saved it (name = personname, nameJob = nil)
 -> I update_attribute('nameJob', nameJob_func(params[:name]))

Is there a better way where I can insert both entries together into the database after I process the nameJob_func()?

1 Answer 1

1

You can create a before_save callback which performs the nameJob_func() function. You therefore never need to call it explicitly, as Rails will call it just before the object is saved. Only the input name needs to be dealt with.

YourModel < ActiveRecord::Base
  # Register nameJob_func as a callback
  before_save :nameJob_func

private
  def nameJob_func
    # Do something with self.name
    self.nameJob = 'something you made here with #{self.name}'
    # This value will get saved to the database automatically
  end
end

Now, whenever the object calls .save(), nameJob_func() runs and gets its updated value from :name.

YourModelsController < ActionController::Base
  def create
    @yourobj = YourModel.new(params[:name])
    # The callback is called and then the whole thing gets saved
    @yourobj.save
  end
end
Sign up to request clarification or add additional context in comments.

2 Comments

It report "wrong number of arguments (0 for 1)" in myModel.rb
@AmySukumunu The nameJob_func used as before_save should have no parameter since it doesn't need them -- it only needs self.name. If that doesn't help, post the full error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.