简体   繁体   English

Rails查看具有相同外键的所有记录

[英]Rails View All records with same foreign key

Currently in my view for each customer I have this: 目前,我认为每个客户都有:

<p>
  <b>Companyname:</b>
  <%= @customer.companyname %>
</p>

<p>
  <b>Licensecontact:</b>
  <%= @customer.licensecontact %>
</p>

<p>
  <b>Email:</b>
  <%= @customer.email %>
</p>

<p>
  <b>Phone:</b>
  <%= @customer.phone %>
</p>

Under that i need to have a table showing all of the licenses associated with that particular customer. 在我需要有一个显示所有与特定客户相关联的许可证的表格。 something like this: 像这样的东西:

<% @licenses.each do |l| %>
<tr>
    <td><%= l.software.vendor %></td>
    <td><%= l.software.title %></td>
    <td><%= l.software.edition %></td>
    <td><%= l.amount %></td>
</tr>
<% end %>

I have three tables, customers, licenses and softwares (I know they're named badly) and one license has many customers and many softwares. 我有三个表,客户,许可证和软件(我知道它们的名称很不好),一个许可证有许多客户和许多软件。

Have you done any tutorials? 你有没有完成任何教程?

  1. Your text contradicts you: you say 'One license has many softwares', but your code says 'License l has one software, and I want to display the name, title and edition'. 您的文字与您矛盾:您说“一个许可证有很多软件”,但是代码却说“许可证l有一个软件,我想显示名称,标题和版本”。
  2. Use belongs_to and has_many. 使用belongs_to和has_many。 On which tables I cannot tell you, because your code syas the opposite of the last line you write. 我无法告诉您哪些表,因为您的代码与您编写的最后一行相反。 But these keywords you need to lookup in the docs, to understand how they work and which migrations to make. 但是您需要在文档中查找这些关键字,以了解它们如何工作以及进行哪些迁移。

Then, if you made the relations in the Models, then you can just call it the way you wrote it down in your second code-part. 然后,如果您在模型中建立了关系,则可以按照在第二个代码部分中写下的方式进行调用。

You should be able to put something like this into your view: 您应该能够将如下所示的内容放入视图中:

<table>
  <tr>
    <th>Vendor</th>
    <th>Title</th>
    <th>Edition</th>
    <th>Amount</th>
  </tr>
  <% @customer.licenses.each do |l| %>
    <tr>
      <td><%= l.software.vendor %></td>
      <td><%= l.software.title %></td>
      <td><%= l.software.edition %></td>
      <td><%= l.amount %></td>
    </tr>
  <% end %>
</table>

From your description it's unclear how customers and licenses are linked together. 根据您的描述,尚不清楚如何将客户和许可证链接在一起。 One option is customer has many licenses, license belongs to one user: 一种选择是客户拥有许多许可证,许可证属于一个用户:

class Customer < ActiveRecord::Base
  has_many :licenses
  # ...
end


class License < ActiveRecord::Base
  belongs_to :customer
  # ...
end

another option is HABTM (you've said 'one license has many customers' and 'table showing all of the licenses associated with that particular customer' which hints me to this): 另一种选择是HABTM(你所说的“一个证拥有众多的客户”和“表显示所有与特定客户相关的许可证”,这暗示我这个):

class Customer < ActiveRecord::Base
  has_and_belongs_to_many :licenses
  # ...
end


class License < ActiveRecord::Base
  has_and_belongs_to_many :customers
  # ...
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM