shoujo_sm
shoujo_sm

Reputation: 3203

RUBY ON RAILS-Get user input to insert into database,process it, insert new variable into database

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()?

Upvotes: 1

Views: 1058

Answers (1)

Michael Berkowski
Michael Berkowski

Reputation: 270609

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

Upvotes: 1

Related Questions