I have to create 3rd table having assosisted with 2nd.
1st table: Schema
2nd table: Entity
3rd table: Fields
Relation between them is:
Schema(id) ===> Entity
Entity(id) ===> Fields
I have created table and views till Entity but don't know how to create table for field
Fields having values as:
"clientId"
"name"
"description"
"mnemonic"
"columnType"
"display"
"fallbackId"
"conceptDisplay"
"businessName"
Help me to create model and views for it to show all the fiels related to entity:
I tried something like this:
entity.rb => model
class Entity < ApplicationRecord
belongs_to :schema
has_many :fields, dependent: :destroy
end
field.rb => model
class Field < ApplicationRecord
belongs_to :entity
end
schema.rb => model
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
views for entity where i have to create link_to to show all field for that entity
<div >
<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>
CodePudding user response:
You need to create these migrations:
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
And add all necessary associations to your models
# 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
Fetch all fields
for Schema
through Entity
in yout controller
# fields_controller.rb
class FieldsController < ApplicationController
def index
@fields = Schema.find_by(id: params[:id]).fields
end
end
And render all links to your fields in view
# views/fields/index.html.erb
<% @fields.each do |field| %>
<%= link_to field.name, field_path(field) %>
<% end %>
And add necessary resources to your routes
# configs/routes
resources :schemas
resources :fields