如何在RoR中管理嵌套关系?

时间:2016-07-04 16:07:21

标签: ruby-on-rails

我是Rails的新手并试图创建一个C2C市场应用程序,只是为了了解rails如何工作并在以后启动一些真实的项目。

这个想法是用户可以将订单发给其他用户。订单与用户的打印机(您选择要在/订购页面上打印的用户)相关。打印机又有许多颜色可供打印

现在,我堆叠着非常基本的东西。

我想在Orders控制器的/ order页面上显示所有拥有所有者姓名和颜色的打印机列表。提前感谢您对我如何做到这一点的任何想法

class User < ActiveRecord::Base
  has_many :printers, dependent: :destroy
  has_many :orders, dependent: :destroy
end


class Order < ActiveRecord::Base
  belongs_to :user
  validates :user_id, presence: true
end


class Printer < ActiveRecord::Base
    belongs_to :user
    validates :user_id, presence: true
    validates :model, presence: true, allow_nil: true

    has_many :materials, dependent: :destroy
end

使用索引操作(/ orders)订购控制器

class OrdersController < ApplicationController
  def index
  @printers = Printer.all
  end   
end

和index.html.erb

<% @printers.each do |p| %>
          <div class="col-xs-9">
            <div><%= "USERNAME HERE" %></div> <!--Do not know how to display parent's model here? -->
            <div><%= p.model %></div> <!--Works fine-->
            <div><%= p.colors.each do |c| c.color end  %></div> <!--Display array instead of strings-->
          </div>
          <div class="col-xs-3">
            <button>Order</button>
          </div>
<% end %>

Simplified schema.db

ActiveRecord::Schema.define(version: 20160627132435) do

  create_table "colors", force: :cascade do |t|
    t.string   "color"
    t.integer  "printer_id"
  end

  create_table "orders", force: :cascade do |t|
    t.string   "price"
    t.string   "status"
    t.integer  "user_id"
  end

  create_table "printers", force: :cascade do |t|
    t.string   "model"
    t.integer  "user_id"
  end

  add_index "printers", ["user_id"], name: "index_printers_on_user_id", using: :btree

  create_table "users", force: :cascade do |t|
    t.string   "first_name"
    t.string   "last_name"
  end

  add_foreign_key "orders", "users"
  add_foreign_key "printers", "users"
end

1 个答案:

答案 0 :(得分:1)

我认为你应该可以做到:

<% @printers.each do |p| %>
          <div class="col-xs-9">
            <div><%= p.user.first_name %></div> <!--Do not know how to display parent's model here? -->
            <div><%= p.model %></div> <!--Works fine-->
            <div><% p.colors.each do |c| 
              <%= c.color %>
            <% end  %></div> <!--Display array instead of strings-->
          </div>
          <div class="col-xs-3">
            <button>Order</button>
          </div>
<% end %>