它看起来像默认:id是整数,我可以把它作为一个字符串?当我使用Active Record时,可以将ID更改为字符串吗?
0
A
回答
3
是的,你可以。
首先运行迁移:
create_table 'table' id: false, force: true do |t|
t.string 'id', null: false
end
指定所述ID的类型string
。
然后在你的模型:
class Table < ActiveRecord::Base
self.primary_key = :id
end
这将基本明确指出该字符串id
是表实例实例的主键。
+0
什么是力量:真正的意思? –
+0
这里是一个完美的解释它的文章:) http://stackoverflow.com/questions/18704290/what-does-force-true-mean-in-the-schema-file – Cyzanfar
0
你也应该考虑在Rails中查找大约uuid
的。
尽管它是主要是PostgreSQL
一块的功能,我们发现它与MYSQL
工作也很好:
你可以将它设置这样的:
#app/models/post.rb
class Post < ActiveRecord::Base
before_create :set_uuid
private
def set_uuid
self.uuid = loop do
random_token = SecureRandom.hex(5)
break random_token unless self.class.exists? random_token
end
end
end
这可以伴随 - 如Cyzanfar
所指出 - 通过用uuid
代替id
主键。 轨道4自动支持uuid
...
def change
create_column :posts, :uuid, :string
remove_column :posts, :id
rename_column :posts, :uuid, :id
execute "ALTER TABLE table ADD PRIMARY KEY (uuid);"
end
一些参考:
- Rails 4. Migrate table id to UUID
- http://www.lshift.net/blog/2013/09/30/changing-the-primary-key-type-in-ruby-on-rails-models/
-
由于Rails 4苏开箱即用的uuid
,这应该适合你。
如前所述,我们使用uuid
我们的一些车型(它使我们能够同时保持独特记录保持功能)
相关问题
- 1. 如果我在Rails中使用MongoDB,我可以使用Active Record关联吗?
- 2. 我可以使用字符串str =“id”,然后person.str = 1吗?
- 3. 我可以使用解压将字符串拆分为Perl中的字符吗?
- 4. 我可以将Unicode字符串转储为字节数组吗?
- 5. 我可以将XText对象更改为字符引用和实体已解析的字符串吗?
- 6. 我可以更改我的开放式ID URL更改吗?
- 7. 使用OnePress时,我可以更改批头的字体吗?
- 8. 我可以使用css将字体更改为圆角字体吗?
- 9. 我可以使用v字符串作为IPv4地址吗?
- 10. 我可以使用scanf作为字符串吗?
- 11. JPA:我可以使用@Column(precision =)作为字符串值吗?
- 12. 使用Castle Active Record的表前缀使用Castle Active Record
- 13. 我可以将列表更改为字符串,修改它,并将其更改为列表?
- 14. 我可以使用Javascript更改HTML元素的ID吗?
- 15. 更新使用Active Record的CI中
- 16. 将大写更改为小写可以缩短字符串的长度吗?
- 17. 我们可以将字符串保存为OpenTSDB中的值吗?
- 18. 我可以更改循环中使用的ID吗?需要在6次迭代中更改1个字符
- 19. Yii-Active Record将特定列的平均结果作为字符串返回
- 20. 当我将adUnitId更改为我自己的字符串id时,广告未显示
- 21. 当我调用SourceAnalyzer - Fortify时,我可以将framework64作为aspnet_compile吗?
- 22. 我可以使用C-preprocssor将整数转换为字符串吗?
- 23. 我可以更改将DataSet保存为xml时使用的缩进样式吗
- 24. 每当预期字符串文字时,可以使用std :: string :: c_str()吗?
- 25. 我们应该什么时候将字符串更改为Stringbuilder?
- 26. 可以在字符串中使用字符串吗?
- 27. TextEncoding可以转换为字符串吗?
- 28. 我可以在PHP字符串中更改制表符宽度(\ t)吗?
- 29. 我可以更改字体大小吗?
- 30. 我们可以设置字符串吗?
你对一个特定的原因是什么? –
选中此项。 http://stackoverflow.com/questions/1200568/using-rails-how-can-i-set-my-primary-key-to-not-be-an-integer-typed-column –