如何添加一列来引用 RoR 上的另一个表?
这是客户:
class CreateCustomer < ActiveRecord::Migration
def self.up
create_table :customers do |t|
t.column :email, :string, :null => false
end
end
def self.down
drop_table :customers
end
end
这是客户信息:
class CustomerInfo < ActiveRecord::Migration
def self.up
create_table :statuses do |t|
t.column :statuses, :string, :null => false
end
end
def self.down
drop_table :status
end
end
我想做的是客户和客户信息具有一对一的关系。我怎样才能在新的迁移中做到这一点?谢谢。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当您想要在 Rails 中实现一对一时,您必须决定哪个模型将存储外键。在您的情况下,您可能希望 status 存储 fk,因此将一个名为
customer_id
的整数列添加到状态表中。然后您可以在 Customer 和 Status 上添加has_one
/belongs_to
。belongs_to
始终使用外键出现在模型上。另外我不确定Rails是否会喜欢你用单数名称来调用你的表,所以如果你真的想将其称为“status”而不是“statuses”,你可能需要做一些额外的工作
When you want a 1 to 1 in Rails, you have to decide which one of the models will store the foreign key. In your case, you probably want status to store the fk, so add an integer column called
customer_id
to the status table. Then you can add thehas_one
/belongs_to
on Customer and Status.belongs_to
always goes on the model with the foreign key.Also I'm not sure if Rails will like you calling your table with the singular name, so you will probably have to do some extra work if you really want to call it 'status' instead of 'statuses'
您可以在下一次迁移中尝试以下操作
add_column :customer_infos , :customer_id , :integer ,:references=>"customers" , :null=>:true
然后您可以在 Customer 和 Cusomer_infos 上添加 has_one/belongs_to 。
您还可以执行 SQL 语句。
statements = "ALTER TABLE users CHANGE id id SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCRMENT" ActiveRecord::Base.connection.execute(statement)
您可以在迁移中手动输入
请注意,这只是一个示例。最终的 SQL 语句语法取决于数据库。
You can try following thing in your next migration
add_column :customer_infos , :customer_id , :integer ,:references=>"customers" , :null=>:true
Then you can add the has_one/belongs_to on Customer and Cusomer_infos .
You can also execute an SQL statement.
statement = "ALTER TABLE users CHANGE id id SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT" ActiveRecord::Base.connection.execute(statement)
you can entry manually in your migration
Note this is just an example. The final SQL statement syntax depends on the database.