In order to setup 1-M relationship
between User
and Stock
model, you would need to define the association as suggested below:
class User < ActiveRecord::Base
has_many :stocks
## ...
end
class Stock < ActiveRecord::Base
belongs_to :user
## ...
end
After this create a foreign_key user_id
in stocks
table as below:
Generate a migration for adding user_id
reference to stocks
table by running:
rails generate migration AddUserRefToStocks user:references
After this run rake db:migrate
NOTE:
make the stocks a nested class of user so each user has their own stocks?
There is no such thing as nested class in Ruby. What you mean probably is how to setup association between User
and Stock
classes.
UPDATE
Change your new
and create
actions in StocksController
as below:
def new
@stock = current_user.stocks.build
end
def create
@stock = Stock.new(stock_params)
if @stock.save
redirect_to @stock, notice: 'Stock was successfully created.'
else
render 'new'
end
end
Also, add a hidden field (within form_for
) in the new
view of stocks
as below:
<%= f.hidden_field :user_id %>
NOTE: Make sure that you permit
the field user_id
in stock_params
method.