Save 36% for Black Friday! Learn more

Rohan Mayya


830 Experience
0 Lessons Completed
1 Question Solved


Posted in How do I create a virtual balance model in Rails?

Hi. Unfortunately I have not subscribed to Gorails, how do I get access to the slack forum? Is there any other way I can contact you? (Maybe skype?) I sent you a request.

Although it does seem correct, nothing seems to be happening when I try to update AccountTransaction.create("enter parameters here"). user balance still remains as "nil".

After creating some basic associations for my AccountTransaction model and moving into my console, I type:

   User.first.account_transactions.create(amount: "1000", transaction_type: "credit", transaction_number:    "1")

With my transaction logic technically this should credit 1000 to my user balance, correct? But User.first.balance still returns nil.

Posted in How do I create a virtual balance model in Rails?

Hey, thanks for the reply. Should I add a column "balance" to my devise user model? Because I intend to show users their remaining balance on their profile. Currently what I've done is, added a balance column to my user model, generated a model called AccountTransactions (transaction_type, amount, user_id and transaction_number). I have also created an "operations" folder (the part that you've called "service class" and have added your code.

How do I proceed from here? Also, could you elaborate on "events" and how to go about them?

EDIT: updating my code (This is from my operations/execute_transactions.rb service class file. Not sure why I have the @transaction_type instance variable specified, not sure what to do with it since it's already being specified within my execute method.

   class StockTransfer
     def initialize(user:, amount:, transaction_type:, quantity:, transaction_number:, stock:)
@user = user
@amount = amount
@transaction_type = transaction_type
@quantity = quantity
#@transaction_number = transaction_number
@stock = stock

 def execute

# logic for the transaction
 # type: (quantity > 0 ? 'credit' : 'debit'),
  event: (quantity > 0 ? 'purchase' : 'sale'),
  stock: @stock,
  transaction_type: (quantity > 0? 'credit' : 'debit')

# insert logic here for the stock transfer
     if transaction_type == "credit"
    @user.update!(balance: @user.balance + @amount)
     elsif transaction_type == "debit"
    @user.update!(balance: @user.balance - @amount)

One more question: How do I default the credited balance amount to 100000 to all users initially?

Posted in How do I create a virtual balance model in Rails?

This is for a game application I'm creating.
I have a user model, a stock model and a UserStock join table for the previous two models. User was created with devise. I intend to attach a certain balance ($100000) that can be used to buy and sell stocks. What's the most efficient way I can get this done? Any guides that can help me with this? Also, anything that can help me configure the buy and sell actions? (Simple action of incrementing the balance when a stock is sold by a user or decrement of balance when a stock is bought)

  1. Nothing is displayed in the view when I add this line.
    EDIT: When I look at my server logs the values returned from user_id, and user_stock all seem to be correct. They're returning the values that are supposed to be returned.
    UPDATE: Oops, on checking again, user_stock = #{user_stock.inspect}" is returning the Stock id in my console and NOT my user_stock association ID. So the fault lies in this variable. (In fact, this variable is returning the entire stock itself, with its name, ticker symbol and price) But isn't it supposed to be returning only the user_stock association ID?

  2. I just generated a migration to add foreign keys for user_stocks to user and stocks, but the user_stocks is still a method that is not defined. (this is what my console tells me)

EDIT: I think I know where I'm going wrong. The table is being iterated with the stocks association and not the user_stock association. I changed it to iterate through the user_stock end, but now how do I call the name, symbol and price variables within the table data?

  1. UserStock.last retrieves UserStock id:6, (user_id:1 and stock_id: 2) which means there have been over 5 associations created just by creating and deleting the same association. (I kept manually destroying the association in my console). I just deleted and recreated the same association again, and it allots UserStock id:7.
    But when I try to use the destroy action in my UI, the rails console still tells me UserStock id:1 cannot be found.
    How am I supposed to work around this?

  2. In your set_user_stock method, user_stocks is a method that isn't defined.

  3. It'd be a pain to remove the method I created and then remove it everywhere but I'll do it when I'm in the process of refactoring code. Thanks for the heads up, didn't know I could directly call a Model.

  4. Yes, it was a typo. Was in a hurry while typing out this question.

How do I go about this? Same error.

I have a user model created through devise, a stock model (generated through a scaffold) so I can create a stocks database with my own custom prices, and a UserStock model to establish an association between the two. Everything seems to run fine in both my UI and my console.

Here's the catch.
I have a delete method tied to a button that is configured in my _list.html.erb, which displays all stocks in the user's portfolio. When I delete it the first time, (remove stock from my portfolio) it works fine. When I add the stock again to my portfolio, works fine of course. But the deletion the second time does not work.

Say, for example, my user ID is 1. My UserStock association creates an association between user_id 1 and stock_id 1 (say stock with id 1 is Google). This is stored in UserStock id 1. When I delete this association and recreate the same, it gets stored in UserStock id 2 (a brand new association). But when I try to delete it again, I'm unable to do so. My rails console indicates this error in my UserStock controller.

This is the error that pops up: Record Not Found in UserStocksController#destroy

  def set_user_stock
   @user_stock= UserStock.find(params[:id])  

Here's my view and the required models:

            <% if == %>
            <%=link_to "Delete", user_stock_path(user_stock), :method 
            => :delete, :data => { :confirm => "Are you sure?" },
            :class => "btn btn-xs btn-danger" %>
            <% end %>


     has_many :user_stocks
     has_many :stocks, through: :user_stocks
     def can_add_stock?(ticker_symbol)

     def stock_already_added?(ticker_symbol)
       stock = Stock.find_by_ticker(ticker_symbol)
       return false unless stock


has_many :user_stocks
has_many :users, through: :user_stocks
def self.find_by_ticker(ticker_symbol)
    where(ticker: ticker_symbol).first


belongs_to :user
belongs_to :stock
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2021 GoRails, LLC. All rights reserved.