Stephen
Stephen

Reputation: 3992

How to preprocessing params when model create in rails?

I have form and pass params:

user_params = { first_name: "Bob", last_name: "A" }

I have a User model which has field full_name, first_name, short_name

So when the params pass to controller, and I call:

@user = User.create(user_params)

I want to store the user with full_name = Bob A, first_name = Bob, short_name = "B.A". Is it possible? If not, where is the best place to transfer the params? before_action in controller?

The key problem is that the form params have different structure with database schema. So a transforming required.

Upvotes: 1

Views: 351

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230346

I prefer extracting this logic into a separate class. I call them "param objects".

# controller
def create
  @user = User.create(ParamObjects::User::Create.new(params).call)
  ...
end

# the param object
module ParamObjects::User
  class Create
    def initialize(params)
      @params = params
    end 

    def call
      { 
        first_name: params[:first_name],
        full_name: compute_full_name,
        short_name: compute_short_name,
      }
    end

    private

    attr_reader :params
    
    def compute_full_name  
      ...
    end
  end
end

But if you're looking for something simpler, Yakov has outlined a couple good options.

Upvotes: 2

Yakov
Yakov

Reputation: 3191

There might be different ways to do it.

Create a method inside a controller:

def prepared_user_params
  user_params.merge(
    full_name: "#{user_params[:first_name]} #{user_params[:short_name]}"
  )
end

Then you can use this method @user = User.create(prepared_user_params).

Or use a callback inside User model.

class User < ApplicationRecord
  before_save :set_full_name

  private
 
  def set_full_name
    self.full_name = "#{first_name} #{short_name}"
  end
end

So, after you call User.create(user_params), first_name and first_name get assigned, full_name gets set by a callback.

Also, it's possible to use some service class that does all the preparations.

Upvotes: 1

Related Questions