我创建了一个简单的 Rails 应用程序,用户可以在其中注册参加活动。为了创造令人愉悦的用户体验,身份不明的用户可以浏览活动,然后如果他们看到他们想参加的活动,他们可以单击“注册活动”。然后,应用程序使用 Twitter Bootstrap 向用户呈现一个模式(弹出窗口),要求他们先注册,以参加活动。
modal上的表格如下:
simple_form_for @user do |f|
f.input :name, :placeholder => "Name", :label => false
f.input :email, :placeholder => "Email", :label => false
f.input :postcode, :placeholder => "Postcode", :label => false
hidden_field_tag :event_id, @event.id
f.button :submit, "Sign me up for this event"
end
因此,您可以看到基本上我将 event_id 值传递给用户控制器的创建操作。为了处理这个,创建动作变成:
def create
if params[:event_id].blank?
event_registration = false
else
event_id = params[:event_id].to_s
event_registration = true
end
if event_registration == true
# The user is being created as part of signing up to an event
@user_check = User.find_by_email(params[:user][:email])
unless @user_check.nil?
# The user already exists, but the visitor forgot
@user = @user_check
else
# The user is a new sign up
@user = User.new(params[:user])
end
# Now create the attendance for the user
@event = Event.find(event_id)
@attendance = @event.attendances.new
@attendance.attendee = @user
@attendance.save
redirect_target = event_attendance_thank_path(@event, @attendance)
else
# The user is being created cleanly
@user = User.new(params[:user])
end
if @user.save
redirect_to root_path, notice: "Thanks for signing up, check your email"
else
# We should destroy the failing attendance?
redirect_to root_path, alert: "Something's up with the signup. Have you already registered with this email address?"
end
end
对我来说,在控制器中处理这种级别的复杂性感觉很混乱,我想知道有什么更好的方法可以解决这个问题?
任何帮助或重构这将不胜感激。