tmartin314
tmartin314

Reputation: 4171

Rails How to call create method with post params from another method

I have a users_controller create method that looks like this:

  def create
    @user = User.new(user_params)
    @user.update_auth_token = true
    @user.mark_as_read_confirmation = 1
    @user.hide_tagged_feeds = 1

    coupon_valid = false
    if user_params['coupon_code']
      coupon = Coupon.find_by_coupon_code(user_params['coupon_code'])
      coupon_valid = (coupon.present? && !coupon.redeemed)
    end

    if coupon_valid || !ENV['STRIPE_API_KEY']
      @user.free_ok = true
    end

    if params[:user] && params[:user][:password]
      @user.password_confirmation = params[:user][:password]
    end

    if @user.save
      unless @user.plan.stripe_id == 'free'
        deactivate_subscriptions = Feedbin::Application.config.trial_days + 6
        send_notice = Feedbin::Application.config.trial_days - 1
        TrialDeactivateSubscriptions.perform_in(deactivate_subscriptions.days, @user.id)
        TrialSendExpiration.perform_in(send_notice.days, @user.id)
        TrialEnd.perform_in(Feedbin::Application.config.trial_days.days, @user.id)
      end
      @analytics_event = {eventCategory: 'customer', eventAction: 'new', eventLabel: 'trial', eventValue: 0}
      flash[:analytics_event] = render_to_string(partial: "shared/analytics_event").html_safe
      sign_in @user
      redirect_to root_url
    else
      render "new"
    end
  end

I am posting some user data and other non-model related data to a separate method in the users_controller. My question is how can I call the create method and set the user_params based on the session variables I have prepared?

Upvotes: 0

Views: 382

Answers (1)

Edgars Jekabsons
Edgars Jekabsons

Reputation: 2853

Emotional side note: Probably one or more kittens die when this code is run. I encourage You to check on some OOP patterns and completely refactor this method. A good introduction to logic extraction concept.

http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

Now to Your question. I am not sure what problems You are having with accessing session data, but actually that's easy. Just like this:

session[:some_field] = "lala"
session[:some_field]
# => "lala"

If You want to manually populate params from session before some controller method just use before_filter (Though sounds like a really bad idea and You are doing something wrong).

class UsersController < ApplicationController
  before_filter :populate_params, only: [ :some_controller_method_like_create ]


private  
  def populate_params
    params[:some_param] = session[:some_param]
  end
end

Upvotes: 1

Related Questions