渲染父轨道4.0的孩子

时间:2014-05-23 16:44:46

标签: ruby-on-rails view render

我有一个具有__ TaskyOrders的合约模型。我试图渲染一个视图,如果我单击“显示”合同行项目,它将显示属于该合同的Task_Orders列表。

这是我的合约架构:

create_table "contracts", force: true do |t|
t.string   "contractId"
t.string   "contractName"

这是我的任务订单架构:

create_table "task_orders", force: true do |t|
t.integer  "contract_Id",              limit: 255
t.string   "task_orderId"
t.string   "task_orderName"

这是我的合约模型:

class Contract < ActiveRecord::Base

has_many :task_orders

end

这是我的任务订单模型:

class TaskOrder < ActiveRecord::Base

belongs_to :contract

end

我不完全确定如何使用控制器和视图来实现它....请帮助。我正在使用Rails 4.0

谢谢。

1 个答案:

答案 0 :(得分:1)

<强> foreign_key

首先,您需要确保为您的关联分配了foreign_keys:

#app/models/task_order.rb
Class TaskOrder < ActiveRecord::Base
   belongs_to :contract, primary_key: "contractID", foreign_key: "contract_Id"
end

#app/models/contract.rb
Class Contract < ActiveRecord::Base
   has_many :task_orders, primary_key: "contractID", foreign_key: "contract_Id"
end

-

<强>控制器

这应该允许您从控制器调用所需的数据:

#app/controllers/contracts_controller.rb
Class ContractsController < ApplicationController
    def show
       @contract = Contract.find params[:id]
    end
end

#app/views/contracts/show.html.erb
<% for order in @contract.task_orders do %>
   <%= order.id %>
<% end %>
相关问题