我必須創建與第二個相關的第三個表。
1st table: Schema
2nd table: Entity
3rd table: Fields
它們之間的關系是:
Schema(id) ===> Entity
Entity(id) ===> Fields
我已經創建了表和視圖,直到物體,但不知道如何為欄位創建表
具有以下值的欄位:
"clientId"
"name"
"description"
"mnemonic"
"columnType"
"display"
"fallbackId"
"conceptDisplay"
"businessName"
幫助我為其創建模型和視圖以顯示與物體相關的所有欄位:
我試過這樣的事情:
entity.rb => 模型
class Entity < ApplicationRecord
belongs_to :schema
has_many :fields, dependent: :destroy
end
field.rb => 模型
class Field < ApplicationRecord
belongs_to :entity
end
schema.rb => 模型
class Schema < ApplicationRecord
has_many :entities, dependent: :destroy
has_many :fields, through: :entities
validates :name, presence: true, uniqueness: true
validates :schemaId, presence: true, uniqueness: true
end
現場控制器:
class FieldsController < ApplicationController
def index
@field = Schema.find_by(id: params[:id]).fields
end
end
我必須創建 link_to 以顯示該物體的所有欄位的物體視圖
<div class="content">
<ul>
<% @entities.each do |data| %>
<li>
<%= data.clientId %>
<%= link_to data.name, fields_index_path(id: data.id) %>
<%= data.description %>
<%= data.mnemonic %>
</li>
<% end %>
</ul>
</div>
uj5u.com熱心網友回復:
您需要創建這些遷移:
def change
create_table :schemas do |t|
# here all your necessary fields for schema
t.timestamps
end
end
def change
create_table :entities do |t|
t.references :schema, null: false, foreign_key: true
# here all your necessary fields for entity
t.timestamps
end
end
def change
create_table :fields do |t|
t.references :entity, null: false, foreign_key: true
# here all your necessary fields for field
t.timestamps
end
end
并將所有必要的關聯添加到您的模型中
# schema.rb
class Schema < ApplicationRecord
has_many :entities
has_many :fields, through: :entities
end
# entiry.rb
class Entity < ApplicationRecord
belongs_to :schema
has_many :fields
end
# field.rb
class Field < ApplicationRecord
belongs_to :entiry
end
fields在您的控制器中Schema獲取所有內容Entity
# fields_controller.rb
class FieldsController < ApplicationController
def index
@fields = Schema.find_by(id: params[:id]).fields
end
end
并在視圖中呈現指向您的欄位的所有鏈接
# views/fields/index.html.erb
<% @fields.each do |field| %>
<%= link_to field.name, field_path(field) %>
<% end %>
并將必要的資源添加到您的routes
# configs/routes
resources :schemas
resources :fields
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/489612.html
標籤:轨道上的红宝石 ruby-on-rails-3 ruby-on-rails-4 ruby-on-rails-7
上一篇:Vulnhub-Venus
