关联在3个table rails中



我必须创建第三个表来辅助第二个。

1st table: Schema
2nd table: Entity 
3rd table: Fields

它们之间的关系为:

Schema(id) ===>  Entity
Entity(id) ===> Fields

我已经创建了表和视图,直到实体,但不知道如何创建表字段

字段值为:

"clientId"
"name"
"description"
"mnemonic"
"columnType"
"display"
"fallbackId"
"conceptDisplay"
"businessName"

帮助我创建模型和视图,以显示与实体相关的所有字段:

我试过这样做:

实体。rb =比;模型

class Entity < ApplicationRecord
belongs_to :schema
has_many :fields, dependent: :destroy
end

字段。rb =比;模型

class Field < ApplicationRecord
belongs_to :entity
end

模式。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

controller for field:

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>

您需要创建这些迁移:

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

获取控制器中SchemaEntity的所有fields

# 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