我是 Ruby 和 RubyOnRails 的新手。到目前为止,我一直在学习基本的 Rails 教程,并创建了多个 View 和 Controller ,以便能够在我的 MySQL 数据库上执行基本的 CRUD,每个 View 和 Controller 都特定于数据库中的表。
我开始了一个新 View ,我希望能够显示来自两个单独表格的信息。我希望能够为他们的契约(Contract)获取客户名称。我觉得这是一个简单而常见的修复方法,我到底忽略了什么?
契约(Contract) View
<table>
<tr>
<th>Contract ID</th>
<th>Customer ID</th>
<th>Discount</th>
<th>Start Date</th>
<th>End Date</th>
<th>Payment Terms</th>
<th>Delivery Day Of Week</th>
<th>Employee ID</th>
<th>Note</th>
<th>Commission</th>
<th>Active</th>
</tr>
<% @contracts.each do |contract| %>
<tr>
<td><%= contract.ContractID %></td>
<td><%= contract.CustomerID %></td>
<td><%= contract.fields_for :customer do |w| %>
<%= w.text_field :CustomerName %>
<% end %>
</td>
<td><%= contract.Discount %></td>
<td><%= contract.StartDate %></td>
<td><%= contract.EndDate %></td>
<td><%= contract.PaymentTerms %></td>
<td><%= contract.DeliveryDayOfWeek %></td>
<td><%= contract.EmployeeID %></td>
<td><%= contract.Note %></td>
<td><%= contract.Commission %></td>
<td><%= contract.Active %></td>
</tr>
<% end %>
</table>
合约模型
> class Contract < ApplicationRecord belongs_to :customer
>
> accepts_nested_attributes_for :customer
> #Validation
>
>
> #Mapping this object to the Database tables self.table_name = "contract" self.primary_key = "ContractID" end
客户模型
> class Customer < ApplicationRecord
>
> has_many :contracts
>
> #Validation validates :CustomerID, :CustomerTypeID, presence: true
>
> validates :CustomerID, uniqueness: true
>
> #Mapping this object to the Database tables self.table_name = "customer" self.primary_key = "CustomerID"
>
> end
契约(Contract) Controller
class ContractsController < ApplicationController
def index
@contracts = Contract.all
@customers = Customer.all
end
end
最佳答案
既然您已经定义了一个客户可能有很多契约(Contract),那么您现在需要定义该契约(Contract)属于一个客户,因此,修改您的模型,它们应该如下所示:
class Contract < ApplicationRecord
belongs_to :customer
...
end
class Customer < ApplicationRecord
has_many :contracts
...
end
现在您可以从某个契约(Contract)访问客户名称属性,例如:
<% @contracts.each do |contract| %>
<%= contract.customer.name %>
<% end %>
这应该可以获取客户名称,但为了改进该查询,您可以在索引操作中添加一个包含:
def index
@contracts = Contract.includes(:customer).all
...
end
关于ruby-on-rails - Rails 如何在一个 View 中访问不同的数据库表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48778216/