Can you please tell me how to display the list of orders of the company when moving from the general list of companies directly to its profile? Output here: views/companies/show.html.erb
Do not judge strictly, I'm just rolling into RoR. Thanks for understanding :)
Working request example with company id=305:
select o.id
from orders as o
inner join users as u ON o.user_id = u.id
inner join companies as c on c.id = u.company_id
where c.id = 305
models/user.rb:
class User < ApplicationRecord
belongs_to :company
has_many :orders
end
models/order.rb
class Order < ApplicationRecord
belongs_to :user
end
models/company.rb:
class Company < ApplicationRecord
has_many :users
end
users_controller.rb:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def index
@users = User.paginate(page: params[:page])
end
end
orders_controller.rb:
class OrdersController < ApplicationController
def show
@orders = Order.find(params[:id])
end
def index
@orders = Order.paginate(page: params[:page])
end
end
companies_controller.rb
class CompaniesController < ApplicationController
def show
@company = Company.find(params[:id])
end
def index
@companies = Company.paginate(page: params[:page])
end
end
views/companies/index.html.erb:
<!DOCTYPE html>
<html>
<%= will_paginate %>
<h1>Company list</h1>
<ul class='companies'>
<% @companies.each do |company| %>
<li>
<%= link_to company.full_name, company %>
</li>
<% end %>
</ul>
<%= will_paginate %>
<html>
views/companies/show.html.erb:
<!DOCTYPE html>
<html>
<div>id: <%= @company.id %></div>
<div>Register date: <%= @company.created_at %></div>
<div>Name: <%= @company.full_name %></div>
<html>
Works in console
orders = Order.joins(user: :company).where(companies: { id: 305 })
CodePudding user response:
First add the missing definition of the association between companies and orders, like this:
# in app/models/company.rb
has_many :users
has_many :orders, through: :users
Then can just call @company.orders
to get the list of orders
associated with @company
.
For example, in your views/companies/show.html.erb
like this:
<!DOCTYPE html>
<html>
<div>id: <%= @company.id %></div>
<div>Register date: <%= @company.created_at %></div>
<div>Name: <%= @company.full_name %></div>
<ul>
<% @company.orders.each do |order| %>
<li>order <%= link_to(order.id, order) %></li>
<% end %>
</ul>
<html>
CodePudding user response:
For example another way, its working:
- Add to companies controller @orders:
def show
@company = Company.find(params[:id])
@orders = Order.joins(user: :company).where(companies: { id: params[:id] })
end
- Add code to show.html.erb:
<div>
Order list of company:
<% @orders.each do |order| %>
<li>
<%= link_to order.id, order %>
</li>
<% end %>
</div>