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

时间:2015-09-30 18:51:39

标签: mysql ruby-on-rails associations

这个问题让我完全陷入困境。我还是在RoR学习新手。

我有两张桌子:台面和计数材料。用户将选择其台面的所有特征,包括材料类型。材料的选项列在Countmaterial表中,并从集合中进行选择。

我的问题是,一旦做出选择并且台面创建了如何在柜台的索引页面上显示材料类型的名称而不是countertype,这是一个生成的整数,以匹配Countmaterial表中的名称?

我宁愿索引显示" Granite"而不是" 1",例如。 "花岗岩"在Countmaterial表中列出,当用户选择" Granite"时,它将Countertop表填充为" 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

你们有什么想法?

1 个答案:

答案 0 :(得分:0)

您会对您的特定型号名称感到困惑;命名模型和控制器时 - 保持简单。一个字......

#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&amp; Ruby是面向对象的。这可能意味着很多,但在使用它们开发应用程序时它非常重要。

Object orientated programming是一种将对象放在代码中心的模式。当你理解它是如何工作的时候,永远不会一样......

enter image description here

传统&#34;编程,您使用用户流程。这被称为event driven programming,虽然适用于标准应用程序,但它不适合Ruby / Rails环境。

Web应用程序具有处理更多数据/功能的能力,因此将所有内容视为对象非常有意义。

因此,无论何时处理Ruby,您都必须从您尝试CRUD (Create Read Update Destroy)的对象的角度考虑所有

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

一旦你看到对象位于Rails如何工作的核心,你就可以构建它周围的一切,如上所述。

相关问题