Specifying column name in a “references” migration

2019-01-12 17:46发布

I want to make a migration in Rails, referencing another table. Usually, I would do something like:

add_column :post, :user, :references

This creates a column named user_id in posts table. But what if, instead of user_id, I want something like author_id? How can I do that?

6条回答
Summer. ? 凉城
2楼-- · 2019-01-12 17:57

In rails 4, when using postgresql and the schema_plus gem you can just write

add_reference :posts, :author, references: :users

This will create a column author_id, which correctly refers to users(id).

And in your model, you write

belongs_to :author, class_name: "User"
查看更多
时光不老,我们不散
3楼-- · 2019-01-12 18:04

Do it manually:

add_column :post, :author_id, :integer

but now, when you create the belongs_to statement, you will have to modify it, so now you have to call

def post
    belongs_to :user, :foreign_key => 'author_id'
end
查看更多
可以哭但决不认输i
4楼-- · 2019-01-12 18:04

In Rails 4.2+ you can also set foreign keys in the db as well, which is a great idea.

For simple associations this can be done also on t.references adding foreign_key: true, but in this case you'll need two lines.

# The migration
add_reference :posts, :author, index: true
add_foreign_key :posts, :users, column: :author_id

# The model
belongs_to :author, class_name: "User"
查看更多
霸刀☆藐视天下
5楼-- · 2019-01-12 18:09

For Rails 5+

Initial Definition:

If you are defining your Post model table, you can set references, index and foreign_key in one line:

t.references :author, index: true, foreign_key: { to_table: :users }

Update Existing:

If you are adding references to an existing table, you can do this:

add_reference :posts, :author, foreign_key: { to_table: :users }

Note: The default value for index is true.

查看更多
Emotional °昔
6楼-- · 2019-01-12 18:10

alias_attribute(new_name, old_name) is very handy. Just create your model and the relationship:

rails g model Post title user:references

then edit the model and add an attribute alias with

alias_attribute :author, :user

After that you'll be able to run things like

Post.new(title: 'My beautiful story', author: User.first)
查看更多
聊天终结者
7楼-- · 2019-01-12 18:11

If you aren't using a foreign key, then it doesn't matter what the actual table name of the other table is.

add_reference :posts, :author

As of Rails 5, if you're using a foreign key, you can specify the name of the other table in the foreign key options. (see https://github.com/rails/rails/issues/21563 for discussion)

add_reference :posts, :author, foreign_key: {to_table: :users}

Prior to Rails 5, you should add the foreign key as a separate step:

add_foreign_key :posts, :users, column: :author_id
查看更多
登录 后发表回答