【问题标题】:Render children of parent rails 4.0渲染父 rails 4.0 的子节点
【发布时间】:2014-05-23 16:44:45
【问题描述】:

我有一个具有_many Task_Orders 的合同模型。我正在尝试呈现一个视图,如果我单击合同行项目的“显示”,它将显示属于该合同的 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

谢谢。

【问题讨论】:

标签: ruby-on-rails view render


【解决方案1】:

foreign_key

首先,您需要确保为您的关联分配外键:

#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 %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-23
    • 2014-11-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多