Reputation: 149
I would like to submit information from my views using a link_to orders controller which I'm not sure how to code.
My models
class User < ApplicationRecord
has_many :orders
has_many :stocks, through: :orders
end
class Order < ApplicationRecord
belongs_to :user
belongs_to :stock
end
class Stock < ApplicationRecord
has_many :orders
has_many :users, through: :orders
end
The way to make orders from the rails console is
order = Order.new
user = User.last
stock = Stock.last
final = user.orders.create(user_id: user.id, stock_id: stock.id)
Routes
Rails.application.routes.draw do
devise_for :users
devise_for :admins
get '/history', to: 'orders#history'
post '/stocks/:id/', to: 'stocks#order', as: 'order_stock'
resources :stocks
root 'stocks#index'
end
I would like to have a single link from app/views/stocks/show to submit orders
Help with the link and controller actions would very appreciate it. Thank you in advance
Upvotes: 0
Views: 104
Reputation: 12524
Since you are about to create
a new order
object; so using POST
as a HTTP method would sound more appropriate. So,
link_to "Order Now!", order_stock_path(params[:id]), method: :post
should work I guess.
In stocks_controller
def order
stock = current_user.stocks.find(params[:id])
stock.order.create
redirect_to stock_path(params[:id]), notice: 'Order created'
end
It should look somewhat this
Note: Rails will send an AJAX POST call to the controller in this case; on success it will redirect accordingly. AJAX code will be embedded near the code to the link. See in the browser your self.
Upvotes: 0