简体   繁体   English

如何让所有表包含Rails 4中的某些列?

[英]How can I make all tables contain certain columns in Rails 4?

Let's assume I'm going to create 10 tables and they have 4 columns in common. 我们假设我要创建10个表,它们共有4列。 Is there an easy way to generate the migration without specifying all 4 columns in each of 10 table's migration file? 是否有一种简单的方法来生成迁移,而无需在10个表的每个迁移文件中指定所有4列?

It's pretty easy to create your own migration helper. 创建自己的迁移帮助程序非常容易。 I'll create a simple one that adds created_by and updated_by columns with a migration helper called userstamps . 我将创建一个简单的,添加created_byupdated_by列,并使用名为userstamps的迁移帮助userstamps

Create an new initializer file config/initializers/userstamps.rb : 创建一个新的初始化文件config/initializers/userstamps.rb

module UserstampMigrationHelper
  def userstamps
    column :created_by, :integer
    column :updated_by, :integer
  end
end

ActiveRecord::ConnectionAdapters::TableDefinition.include(UserstampMigrationHelper)

Now you can use it in a migration: 现在您可以在迁移中使用它:

class WidgetsMigration < ActiveRecord::Migration
  def change
    create_table :widgets do |t|
      t.string :name
      t.userstamps
    end
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何指定所有表应包含某些字段? - How can I specify that all tables should contain certain fields? rails:如何建立到某个动作的多态链接 - rails: how can I make a polymorphic link to a certain action 模型有一个由字符串数组组成的字段,如何查找数组中包含某个字符串的所有记录? - Model has a field which is an array of strings, how can I find all records that contain a certain string in the array? 如何在特定表格中显示特定属性,而不为当前用户显示所有属性RAILS 4 - How can i display a certain attribute in a certain table without displaying all for a current user RAILS 4 Rails:如何使对象在所有视图中可用? - Rails: How can I make an object available in all views? Rails:对基础表进行更改后,如何重新生成脚手架创建的所有视图? - Rails: How can I regenerate all the views created by scaffold after I make changes to the underlying table? 如何在Rails控制器中访问某些数据库表? - How to access certain database tables in Rails controller? Rails-使用Redcarpet作为Markdown解释器,如何使所有链接具有html targer _blank属性? - Rails - Use Redcarpet as Markdown interpreter, how can I make all links have a html targer _blank attribute? 除非在Rails表单中另外指定,否则我如何使所有字段都是必需的? - How can I make all fields required unless specified otherwise in Rails forms? Rails - 如何创建一个完全没有命中数据库的请求? - Rails - how can I make a request that doesn't hit the database at all?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM