Rails refactoring a method

im a new developer and i need some help to refactor this code

So, I have a Rails App with a controller called subscription_signups. There i have a New method, that helps me create a Subscription, and it executes a private method called add_plan_to_cookies.

This is my controller

  def new
    @subscription_signup = SubscriptionSignup.new(account_id: current_account.id)
    add_plan_to_cookies
  end

  private 
  
   def add_plan_to_cookies
    plan = current_account.base_plans.find_by(id: params[:base_plan])&.current_plan
    remember_plan(plan.id) if plan.present?
    @plan = current_account.base_plans.find_by(id: cookies.signed[:plan])&.current_plan
  end

def remember_plan(plan)
  cookies.signed[:plan] = plan
end 

In the add_plan_to_cookies method, the plan is obtained through the base_plan_id and then another method called remember_plan is executed and saves the plan in a cookie. What i have to do is using the plan that was saved in the cookie. & I can obtain that with the second query, but there has to be a better way.

So first I get the ID of the params, look for the plan and add its id to the cookies. Then i have to use that id to search for the plan that you already got before.

MY problem is that the im doing too queries for something that is kind of the same, and i dont now have to refactor it. anyone has a suggestion?

In the view i have something like this.

<% if @plan.present? %>
  <%= @plan.name %>
  <%= image_tag @plan.base_plan.cover(:medium), class: "img-responsive "%>
<% end %>


from Recent Questions - Stack Overflow https://ift.tt/3uxsRhv
https://ift.tt/eA8V8J

Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation