Deano
Deano

Reputation: 12190

How to save Rails input parameters to file

I created a small application using scaffold. I'm posting data via the chrome "PostMan" extension.

This is the default create method in my controller:

# POST /settings
  # POST /settings.json
  def create
    @setting = Setting.new(setting_params)

    respond_to do |format|
      if @setting.save
        format.html { redirect_to @setting, notice: 'Setting was successfully created.' }
        format.json { render :show, status: :created, location: @setting }
        puts Setting.new(setting_params).to_yaml 

      else
        format.html { render :new }
        format.json { render json: @setting.errors, status: :unprocessable_entity }
      end
    end
  end

This is the log in Rails' console:

(0.2ms)  begin transaction
  SQL (1.0ms)  INSERT INTO "settings" ("DetectionOnly", "SecRequestBodyAccess", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["DetectionOnly", "f"], ["SecRequestBodyAccess", "f"], ["created_at", "2016-03-23 18:04:42.642492"], ["updated_at", "2016-03-23 18:04:42.642492"]

I'm trying to only log this transaction into a file and save output in YAML format .

I tried adding this right after @setting.save.

   puts Setting.new(setting_params).to_yaml 

What am I doing wrong here?

Upvotes: 0

Views: 443

Answers (1)

vee
vee

Reputation: 38645

If you want to save the yaml to a separate file, you could open the file in append mode and append the yaml as follows in your create action where you have puts...:

...
settings_param_file = ... # File path
if @setting.save
  File.open(settings_param_file, 'a') do |file|
    file << Setting.new(setting_params).to_yaml
  end
end

Also, using puts in your controller action should be considered invalid. Instead you should use Rails.logger or just logger in your controller. To log a debug message use:

logger.debug { Setting.new(setting_params).to_yaml }

Upvotes: 1

Related Questions