ruby 如何在一个类的表示中显示另一个类的示例?

0yycz8jy  于 2022-12-29  发布在  Ruby
关注(0)|答案(2)|浏览(121)

您能告诉我从公司总列表直接移动到其个人资料时,如何显示该公司的订单列表吗?在此处输出:查看/公司/显示.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 })
iklwldmw

iklwldmw1#

首先添加缺少的公司和订单之间关联的定义,如下所示:

# in app/models/company.rb
has_many :users
has_many :orders, through: :users

然后可以调用@company.orders来获取与@company关联的orders列表。
例如,在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>

  <ul>
    <% @company.orders.each do |order| %>
      <li>order <%= link_to(order.id, order) %></li> 
    <% end %>
  </ul>
<html>
ruoxqz4g

ruoxqz4g2#

例如另一种方式,它的工作:
1.添加到公司控制器@订单:

def show
    @company = Company.find(params[:id]) 
    @orders = Order.joins(user: :company).where(companies: { id: params[:id] })
  end

1.添加代码以显示.html.erb:

<div>
Order list of company:
  <% @orders.each do |order| %>
    <li>
      <%= link_to order.id, order %> 
    </li>
  <% end %>
</div>

相关问题