如何调用关联模型的方法

时间:2013-05-20 15:01:59

标签: ruby-on-rails

我有一个带有User.rb类和Promember.rb类的Rails应用程序。 Promember.rb belongs_to:user和User.rb has_one:promember。

在我的Promember.rb模型中,我使用以下update_stripe方法(改编自本教程https://tutorials.railsapps.org/tutorials/rails-stripe-membership-saas)来处理通过Stripe注册promembership。如果没有customer_id存在(即,如果它是新客户),当我调用Stripe :: Customer.create方法时,我从关联的用户实例(至少那是我认为我正在做的)中获取电子邮件和名称信息< / p>

  :email => user.email,
  :description => user.name,

这适用于创建新的Stripe客户,但在customer_id存在的情况下(我没有创建新客户),尝试从用户那里获取名称和电子邮件

  customer.description = user.name
  customer.email = user.email

我收到此错误

NoMethodError in PromembersController#create
undefined method `name' for nil:NilClass

为什么'用户'在这种情况下会为零?

    def update_stripe

    if customer_id.nil?

        customer = Stripe::Customer.create(
          :email => user.email,
          :description => user.name,
          :card => stripe_token,
          :plan => '1'
        )

    else
      customer = Stripe::Customer.retrieve(customer_id)
      if stripe_token.present?
        customer.card = stripe_token
      end
      customer.description = user.name
      customer.email = user.email
      customer.save
    end
    self.last_four_digits = customer.active_card.last4
    self.customer_id = customer.id
    self.stripe_token = nil
  rescue Stripe::StripeError => e
    logger.error "Stripe Error: " + e.message
    errors.add :base, "#{e.message}."
    self.stripe_token = nil
    false
  end

更新

这是创建操作(在Rails 4应用程序中使用强参数)

def create
    @promember = current_user.build_promember(promember_params)

 if @promember.save
    current_user.add_role :pro

  redirect_to   lawyer_profile_path(current_user), :notice => "award created question. It will be reviewed if you checked box"
else

    redirect_to (:back),  :notice => "There was an error."

  end 
end



  private
def promember_params

  params.require(:promember).permit(:pro, :customer_id, :user_id, :last_four_digits, :stripe_token, :stripe_card_token)
end

更新

这些是传递给create方法的参数

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"3zq3tFwp1AgR3yBWGenW45kLqUzVlg96dP8Haa4bVKQ=", "promember"=>{"stripe_token"=>""}, "commit"=>"Create Promember"}
{"utf8"=>"✓", "authenticity_token"=>"3zq3tFwp1AgR3yBWGenW45kLqUzVlg96dP8Haa4bVKQ=", "promember"=>{"stripe_token"=>""}, "commit"=>"Create Promember", "action"=>"create", "controller"=>"promembers"}
promemberparams
  User Load (0.6ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 22 ORDER BY "users"."id" ASC LIMIT 1
  Promember Load (31.4ms)  SELECT "promembers".* FROM "promembers" WHERE "promembers"."user_id" = $1 ORDER BY "promembers"."id" ASC LIMIT 1  [["user_id", 22]]
   (0.2ms)  BEGIN
   (0.3ms)  ROLLBACK
Completed 500 Internal Server Error in 3586ms

NoMethodError (undefined method `name' for nil:NilClass):
  app/models/promember.rb:38:in `update_stripe'
  app/controllers/promembers_controller.rb:16:in `create'

0 个答案:

没有答案