简体   繁体   English

如何定义Rails模型设置的架构?

[英]How do define the schema that a rails model is set to?

For instance, when I generate an Event model, the table automatically sets to the public schema. 例如,当我生成事件模型时,该表会自动设置为公共模式。 How do I specify it to get set to a different schema? 如何指定它以设置为其他架构?

Furthermore, how do you alter the schema of an existing table? 此外,如何更改现有表的架构? Perhaps move it to a different schema? 也许将其移至其他架构?

Thank you! 谢谢!

Disclaimer: I don't know rails, so I'm going to give very postgresql-oriented answers here. 免责声明:我不知道rails,所以在这里我将给出非常面向PostgreSQL的答案。 For the first part of your question, there is quite possibly a much better way to do this, by making rails specify the schema when creating tables. 对于您的问题的第一部分,通过在创建表时使rails指定架构,可能有一种更好的方法。

In PostgreSQL, tables are searched for in schemas according to the search_path setting. 在PostgreSQL中,将根据search_path设置在模式中搜索表。 This is set by default to "$user",public . 默认情况下,此设置为"$user",public Tables are created in the first schema found in the search path that exists. 在存在的搜索路径中找到的第一个架构中创建表。 So if you connect as "my_user", it will try to create tables in "my_user", and fall back to creating them in "public" if "my_user" doesn't exist. 因此,如果以“ my_user”身份连接,它将尝试在“ my_user”中创建表,如果“ my_user”不存在,则将退回到在“ public”中创建表。

So one approach is to update the "search_path" setting used for the user you connect to the database to make schema changes. 因此,一种方法是更新用于连接数据库的用户的“ search_path”设置,以进行模式更改。 For example you can say ALTER USER my_user SET search_path = my_app, public . 例如,您可以说ALTER USER my_user SET search_path = my_app, public If you then create a "my_app" schema then subsequent CREATE TABLE foo(...) commands executed by "my_user" will put the new table into "my_app". 如果随后创建“ my_app”模式,则随后由“ my_user”执行的CREATE TABLE foo(...)命令会将新表放入“ my_app”。

You can change the schema of a table using ALTER TABLE foo SET SCHEMA my_app . 您可以使用ALTER TABLE foo SET SCHEMA my_app的架构。

Create a migration to generate your new schema. 创建迁移以生成新的架构。 ActiveRecord can't update you schema to you it's the pattern system. ActiveRecord无法将您的模式更新为模式系统。 You can try sequel or DataMapper if you want update you schema from your code. 如果要从代码更新架构,可以尝试使用续集或DataMapper。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM