I am having some trouble finding a good answer to my question on rails relationship creation.
If I already ran the initial migration for my user model and my comment model Without declaring a relationship (ie: a user has_many comments, and comments belong_to user) how do I define that relationship later on?
Can I simply: 1-add the user_id column to Comments, 2-declare the relationship and 3-run the new add_user_id_to_comm开发者_StackOverflow社区ent migration file?
Will this work? If not, how would I go about changing the relationship after already having ran the initial migration for the models? Thank you so much for your help.\
Rails 3.1, Ruby 1.8.7
You can just add the reference in another migration, using the change_table
migration (documentation):
change_table :comments do |t|
t.references :user
end
Then just add the associations to your models.
class User < ActiveRecord::Base
has_many :comments
end
class Comment < ActiveRecord::Base
belongs_to :user
end
精彩评论