0

嘿伙计们,我正在尝试使用长臂猿 gem 集成 Mailchimp API,但我一直在保存error undefined method'`。

我的控制器代码:

class LandingPageController < ApplicationController

layout 'landing_page'

def index

@subscriber = Subscriber.new

end




def create
    # Instantiate a new object using form parameters

    @subscriber = Subscriber.new(subscriber_params)

    # Save the object
    if @subscriber.save 
      @subscriber.valid?
      @subscriber.subscribe
      # If save succeeds, redirect to the index action
      flash[:notice] = "Thank You for subscribing. Your Email ID has been entered successfully into our database."

      redirect_to(:action => 'index')
    else
      # If save fails, redisplay the form so user can fix problems

      render('index')
    end
  end







  private

    def subscriber_params
      # same as using "params[:subject]", except that it:
      # - raises an error if :subject is not present
      # - allows listed attributes to be mass-assigned
      params.require(:subscriber).permit(:email)
    end

end

这在开始集成之前运行良好。所以为了调试我删除的错误@subscriber.save,看看会发生什么。然后我得到一个新的错误uninitialized constant Gibbon::Request in subscriber.rb。我的subscriber.rb 代码:

class Subscriber
  include ActiveModel::Model
  attr_accessor :email, :string
  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::Request.new(api_key: Rails.application.secrets.mailchimp_api_key)

    result = mailchimp.lists.subscribe({
      :id => Rails.application.secrets.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

我已经尝试了至少十几种不同的修复方法。我尝试了不同版本的长臂猿宝石,似乎没有任何效果。我尝试对我的 API 密钥进行硬编码,而不是从 secrets.yml 中获取它。我现在已经没有选项了,还有其他关于谷歌的问题。我的问题似乎没有解决方案。

如果您需要我项目中的任何其他代码,我们将不胜感激。

编辑:

我能够undefined method save通过添加ActiveRecord::Base而不是删除错误include ActiveModel::Model。但我仍然得到uninitialized constant Gibbon::Request错误。

4

1 回答 1

1

您的代码有几个问题:

  • 如果您的错误是uninitialized constant Gibbon::Resquest in subscriber.rb,那么您可能拼错了Request
  • save是一种ActiveRecord方法,而不是一种方法ActiveModel。所以你的模型应该继承ActiveRecord::Base而不是包括ActiveModel::Model;
  • 除非您包含ActiveModel::Validations.

话虽如此,您使用的宝石没有问题。如果您将正确的超类添加到您的模型并删除include,那么事情应该会按预期工作。

关于常量的持久性没有被找到,你有没有加gem 'gibbon'进去Gemfile然后运行bundle?要检查,启动 Rails 控制台并查看 gem 是否已加载:

$ rails c
>> Gibbon
...
>> Gibbon::Request
...
于 2015-11-25T21:36:48.220 回答