我有users_controller
create
方法,如下所示:
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
我将一些用户数据和其他非模型相关数据发布到users_controller
中的单独方法。我的问题是如何调用create方法并根据我准备的会话变量设置user_params?
答案 0 :(得分:1)
情绪侧注:运行此代码时,可能会有一只或多只小猫死亡。我鼓励你检查一些OOP模式并完全重构这个方法。对逻辑提取概念的一个很好的介绍。
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/
现在回答你的问题。我不确定您访问会话数据时遇到了什么问题,但实际上这很容易。就像这样:
session[:some_field] = "lala"
session[:some_field]
# => "lala"
如果你想在某些控制器方法使用before_filter
之前手动填充会话中的参数(虽然听起来真的很糟糕,你做错了什么)。
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