[英]Associated in 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"
帮助我为其创建模型和视图以显示与实体相关的所有字段:
我试过这样的事情:
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>
您需要创建这些迁移:
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
通过您控制器中的Entity
获取Schema
的所有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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.