如何在 Rails 中显示名称而不是 Id

How to Show Name Instead of Id in Rails

这个问题把我难住了。我在 RoR 和学习方面仍然是新手。

我有两个 table:Countertops 和 Countmaterial。用户将 select 台面的所有功能,包括 material 类型。 material 的选项列在 Countmaterial table 中,并且 selection 来自一个集合。

我的问题是一旦制作了 selection 并创建了 Countertop,我如何在 Countertops 的索引页面上显示 material 类型的名称而不是 countertype,这是一个生成的整数以匹配 Countmaterialtable 中的名称?

例如,我宁愿索引显示 "Granite" 而不是“1”。 "Granite" 列在 Countmaterial table 中,当用户 selects "Granite" 时,它将 Countertop table 填充为“1” countertype 列。大理石是“2”等等...

这是我的架构:

create_table "countertops", force: :cascade do |t|
 t.string   "size"
 t.string   "color"
 t.datetime "created_at",  null: false
 t.datetime "updated_at",  null: false
 t.string   "ZipCode"
 t.string   "countertype"
end

create_table "countmaterials", force: :cascade do |t|
 t.string   "name"
 t.datetime "created_at",    null: false
 t.datetime "updated_at",    null: false
 t.integer  "countertop_id"
end

我的索引台面控制器:

def index
 @countertops = Countertop.all
 @countertops = Countertop.includes(:countmaterial).all
end

我的索引代码:

<% @countertops.each do |countertop| %>
  <tr>
    <td><%= countertop.ZipCode %></td>
    <td><%= countertop.countmaterial.name %></td>

协会:

class Countertop < ActiveRecord::Base
  has_one :countmaterial
end

class Countmaterial < ActiveRecord::Base
  belongs_to :countertop
end

大家怎么看??

您会对特定的型号名称感到困惑;命名模型和控制器时——保持超级简单。一句话...

#app/models/counter.rb
class Counter < ActiveRecord::Base
   #columns id | type_id | material_id | size_id | color_id | zip_code| created_at | updated_at
   belongs_to :type
   belongs_to :material
   belongs_to :size
   belongs_to :color
   delegate :name, to: :size, prefix: true
end

#app/models/option.rb
class Option < ActiveRecord::Base
   #columns id | Type | name | created_at | updated_at
   has_many :counters
end

#app/models/size.rb
class Size < Option
end

#app/models/type.rb
class Type < Option
end

#app/models/color.rb
class Color < Option
end

#app/models/material.rb
class Material / Option
end

这将使您能够执行以下操作:

#config/routes.rb
resources :counters

#app/controllers/counters_controller.rb
class CountersController < ApplicationController
   def index
      @counters = Counter.all
   end
end

#app/views/counters/index.html.erb
<% @counters.each do |counter| %>
   <%= counter.size_name %>
<% end %>

为了让您了解其工作原理,您需要知道 Rails 和 Ruby 是 面向对象的。这可能意义不大,但在使用它们开发应用程序时非常重要。

Object orientated programming 是一种将 对象 置于代码中心的模式。当您了解其工作原理后,永远不会相同...

在 "traditional" 编程中,您使用用户流程。这称为 event driven programming,虽然适用于标准应用程序,但不适合 Ruby/Rails 环境。

Web 应用程序有能力处理如此多的数据/功能,因此将一切都视为一个对象非常有意义。

因此,每当您处理 Ruby 时,您都必须从您要处理的对象 CRUD (Create Read Update Destroy) 的角度来考虑 一切

这就是为什么您的 CounterTop 模型有点粗略 - 您尝试调用的 对象 是什么?

一旦您看到 对象 位于 Rails 工作原理的核心位置,您将能够围绕它构建一切,如上所述。