您能告诉我从公司总列表直接移动到其个人资料时,如何显示该公司的订单列表吗?在此处输出:查看/公司/显示.html.erb
不要严格判断,我只是滚动到RoR。感谢理解:)
公司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
型号/用户.rb:
class User < ApplicationRecord
belongs_to :company
has_many :orders
end
型号/订单.rb
class Order < ApplicationRecord
belongs_to :user
end
型号/公司。rb:
class Company < ApplicationRecord
has_many :users
end
用户_控制器.rb:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def index
@users = User.paginate(page: params[:page])
end
end
订单_控制器.rb:
class OrdersController < ApplicationController
def show
@orders = Order.find(params[:id])
end
def index
@orders = Order.paginate(page: params[:page])
end
end
公司_控制器.rb
class CompaniesController < ApplicationController
def show
@company = Company.find(params[:id])
end
def index
@companies = Company.paginate(page: params[:page])
end
end
浏览次数/公司/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>
浏览次数/公司/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>
在控制台中工作
orders = Order.joins(user: :company).where(companies: { id: 305 })
2条答案
按热度按时间iklwldmw1#
首先添加缺少的公司和订单之间关联的定义,如下所示:
然后可以调用
@company.orders
来获取与@company
关联的orders
列表。例如,在
views/companies/show.html.erb
中,如下所示:ruoxqz4g2#
例如另一种方式,它的工作:
1.添加到公司控制器@订单:
1.添加代码以显示.html.erb: