Question

I currently have Users with a Subcribed Boolean value set to False.

How can i change the value once the User creates a subscription?

I have written my code below....New to Rails please help :)

MODELS

class User < ActiveRecord::Base
  attr_accessible :name, :username, :email, :subscribed

  has_one :subscription, :dependent => :destroy

end

class Subscription < ActiveRecord::Base
  attr_accessible :plan_id, :user_id, :email

  belongs_to :plan
  belongs_to :user

  after_create :subscribed

  def subscribed    ***This is my current code
    if self.user.subscribed == false
      self.user.subscribed = true
    end
  end

  def save_with_payment
    if valid?
      save_with_stripe_payment
    end
  end

  def save_with_stripe_payment
    customer = Stripe::Customer.create(card: stripe_card_token, email: email, plan: plan_id, description: "Unlimited Comics")
    self.stripe_customer_token = customer.id
    save!
  rescue Stripe::InvalidRequestError => e
    logger.error "Stripe error while creating customer: #{e.message}"
    errors.add :base, "There was a problem with your credit card."
    false
  end

end

CONTROLLERS

class SubscriptionsController < ApplicationController

  def new
    plan = Plan.find(params[:plan_id])
    @subscription = plan.subscriptions.build
    @subscription.user_id = current_user.id
  end

  def create
    @subscription = Subscription.new(params[:subscription])
    if @subscription.save_with_payment
      redirect_to @subscription, :success => "Thank you for subscribing!"
    else
      render :new
    end
  end

end

SHEMA

  create_table "users", :force => true do |t|
    t.string   "name"
    t.string   "email"
    t.boolean  "subscribed",             :default => false    ***change to True
    t.string   "username"
  end

  create_table "subscriptions", :force => true do |t|
    t.integer  "plan_id"
    t.integer  "user_id"
  end
Was it helpful?

Solution

Try following

after_create :subscribed

def subscribed
  self.user.update_attribute(:subscribed, true) unless self.user.subscribed
end

OTHER TIPS

 def subscribed    ***This is my current code
    if self.user.subscribed == false
      self.user.subscribed = true
    end
  end

After self.user.subscribed = true add self.user.save

If you have mentioned the relation correctly

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top