'In rails i have two method for both create and update the params but both do a similar job how i use same method for both create and update

i have two method like in leadercontroller

def create_params
        params.permit(:name, :sur_name, :image_url, :position, :linked_in_url, :twitter_url, :status)
      end

      def update_params
        params.permit(:name, :image_url, :position, :linked_in_url, :twitter_url, :status)
      end

I need update and create it on base API controller

  def create
    object = klass.create!(create_params)
    render json: {
      status: true,
      message: 'Saved Successfully..!',
      data: object_json(object),
    }, status: :created
  end

  def update
    object.update!(update_params)
    render json: {
      status: true,
      message: 'Saved Successfully..!',
      data: object_json(object),
    }
  end`


Solution 1:[1]

Rails convention points you to have a single method for fetching the params.

class LeaderController

def create
  object = klass.create!(leader_params)
  ...add your logic here
end

def update
  object = klass.update!(leader_params)
  ...add your logic here
end

private
  def leader_params
    params.permit(:name, :sur_name, :image_url, :position, :linked_in_url, :twitter_url, :status)
  end

No matter if you have :sur_name parameter received only in create_params method. If not submitted, it won't be applied on params prepare.

Check docs and basic example here: https://guides.rubyonrails.org/action_controller_overview.html

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1