我觉得我在这里缺少一些简单的东西。我设置了一个MailChimp邮件列表,我试图让注册按钮工作但是提交错误。我将它路由回控制器中create方法的根目录但它不起作用。
signup.rb
class Signup < ActiveRecord::Base
validates_presence_of :email
validates_format_of :email, :with => /\A[-a-z0-9_+\.]+\@([-a-z0-9]+\.)+[a-z0-9]{2,4}\z/i
def subscribe
mailchimp = Gibbon::API.new
result = mailchimp.lists.subscribe({
:id => ENV['MAILCHIMP_LIST_ID'],
:email => {:email => self.email},
:double_optin => false,
:update_existing => true,
:send_welcome => true
})
Rails.logger.info("Subscribed #{self.email} to MailChimp") if result
end
end
signups_controller.rb
class SignupsController < ApplicationController
def new
@signup = Signup.new
end
def create
@signup = Signup.new(secure_params)
if @signup.valid?
redirect_to root_path
else
render :new
end
end
private
def secure_params
params.require(:signup).permit(:email)
end
end
的routes.rb
Rails.application.routes.draw do
root 'pages#index'
get '/about' => 'pages#about'
get '/tour' => 'pages#tour'
get '/music' => 'pages#music'
resources :signups, only: [:new, :create]
end
我可以在routes.rb中添加什么来发布?这是我的佣金路线输出...
Prefix Verb URI Pattern Controller#Action
root GET / pages#index
about GET /about(.:format) pages#about
tour GET /tour(.:format) pages#tour
music GET /music(.:format) pages#music
signups POST /signups(.:format) signups#create
new_signup GET /signups/new(.:format) signups#new
提前致谢!
答案 0 :(得分:0)
更改
<%= simple_form_for :signup do |f| %>
的
<%= simple_form_for @signup do |f| %>
然后您将转到SignupsController#create
。
除此之外,您需要在代码中的任何位置调用Signup#subscribe
以使整个表单生效。您可能也希望将注册保存到数据库中。我建议在控制器中进行此更改:
def create
@signup = Signup.new(secure_params)
if @signup.save && @signup.subscribe
redirect_to root_path
else
flash[:error] = 'Ooops!'
render :new
end
end
并且如果true
成功,请记得从Signup#subscribe
返回result
。