I thought it would be nice if there was a key name list for display when creating the list screen.
Create some model
models/user.rb
class User < ApplicationRecord
include Table #If you include it here, you can use it as an instance method
attribute :name
attribute :email
attribute :login_id
attribute :password
end
models/concerns/table.rb
module Table
extend ActiveSupport::Concern
#Get column name (symbol) as an array
def table_keys
self.class.column_names.map(&:to_sym).reject { |column| %i[id created_at updated_at].include?(column) }
#Click here if you want to get it as a character string
# self.class.column_names.reject { |column| %w[id created_at updated_at].include?(column) }
end
#Get column name
def col_name(column_name)
self.class.human_attribute_name(column_name)
end
end
from
@ useretc. with
self.class`column_names.map (&: to_sym)
and convert it to a symbolreject { |column| %w[id created_at updated_at].include?(column) }
Exclude unnecessary column names inruby:views/users/index.html.slim
- if @users.present?
table.table
thead
tr
- first_user = @users.first
- first_user.table_keys.each do |key|
= tag.td first_user.col_name(key)
tbody
- @users.each do |user|
tr
- user.table_keys.each do |key|
= tag.td {|tag| tag.span user.send(key)}
- else
p No data
This kind of screen is often used for devise and active_admin, but it seems that it can also be used when passing the validation key to the front side.
If you have any advice, please do not hesitate to contact us.
Recommended Posts