t。模型中迁移vs belongs_to的参考?
我正在阅读Rails指南,我找到了以下代码行:
class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| t.string :commenter t.text :body t.references :post t.timestamps end add_index :comments, :post_id end end
我还阅读了Michael Hartl的书,Rails Tutorial,我没有找到任何关于上面代码中使用的“t.references”的内容。 它有什么作用? 在Michael的书中,我在模型中使用了has_many和belongs_to关系,而在迁移中没有使用任何关系(不是事件t.belongs_to)。
这是Rails最近的一个新增function,所以你提到的这本书可能没有涉及到它。 您可以在Rails指南的迁移部分中阅读它。
当你使用生成时,比方说,
rails generate model Thing name post:references
…迁移将为您创建外键字段,以及创建索引。 这就是t.references
所做的。
你本来可以写的
rails generate model Thing name post_id:integer:index
得到了相同的最终结果。
请参阅Rails指南的这一部分 。
在您的情况下, t.references
在您的comments
表中创建一个post_id
列。 这意味着Comment属于Post,所以在Comment
模型中你必须添加belongs_to :post
和post模型: has_many :comments
。
- 奇怪的问题has_many通过更新Rails中的关联
- ActiveRecord create:传入属性数组
- ActiveRecord … activerecord-mysql-adapter
- postgresql,奇怪的OFFSET / LIMIT行为(记录顺序)
- first_or_create vs find_or_create_by
- ActiveModel :: SecurePassword未定义方法`password_digest =’
- Ruby on Rails:ActiveRecord对象创建的确认页面
- Rails:在每个请求上切换连接但保留连接池
- Rails gem rails3-jquery-autocomplete:如何查询多个字段