0

I have these models on Rails :

class Tweet < ActiveRecord::Base
  attr_accessible :status
  belongs_to :user
end

class User < ActiveRecord::Base
  attr_accessible :name
  has_many :tweets
end

but on bd there isn't a relationship between these models. Which migration i need to do for add user_id into tweet table?

Emanuele Pavanello
  • 785
  • 1
  • 9
  • 22

2 Answers2

3

You need to add the user_id into your Tweet model then in your model you can do:

run rails g migration add_user_id_to_tweets user_id:integer

Which will give you the following output

  class AddUserIdToTweet < ActiveRecord::Migration
  def change
    add_column :tweets, :user_id, :integer
  end
end
Deej
  • 5,334
  • 12
  • 44
  • 68
  • As I know there is no need to add foreign key as this is used by default, you set foreign key if you want to tie this table using an attribute different to user_id – rmagnum2002 May 29 '13 at 21:12
  • @rmagnum2002 - Check this guide: http://guides.rubyonrails.org/migrations.html#changing-tables – Deej May 29 '13 at 21:14
  • @rmagnum2002 Pretty sure the child needs a foreign_key, else I've been doing Rails associations / SQL completely wrong for the past couple of years ;). Also I'd change the order of code snippets there to save confusion, the migration file gets auto-generated with that last command. – Noz May 29 '13 at 21:16
  • `add_column :tweets` (plural needed here) – MrYoshiji May 29 '13 at 21:17
  • foreign_key ?? never used it in my apps, only if I need to refer to another column, like in case instead user_id I'll use person_id – rmagnum2002 May 29 '13 at 21:19
  • @rmagnum2002 Sorry that statement might have been confusing, I should have said 'Pretty sure the child needs a foreign key'. If you don't have a foreign key in the child table SQL won't know what primary key to reference for the parent. – Noz May 29 '13 at 21:22
  • @Cyle I was talking about the first answer where David added has_many: tweets, foreign_key: user_id and I was saying there is no need to use it as long as you have user_id in table. Never said that we don't need user_id in database – rmagnum2002 May 29 '13 at 21:22
  • @rmagnum2002 Oh crap, I see what you mean. Sorry I didn't see David's first edit. :P – Noz May 29 '13 at 21:25
2

There is the migration to run:

change_table :tweets do |t|
  t.references :user
end

This will add a column named user_id to the tweets table. (Don't forget to run a rake db:migrate to update the Database!)

Documentation of change_table (ActiveRecord::ConnectionAdapters::SchemaStatements) - APIdock

MrYoshiji
  • 54,334
  • 13
  • 124
  • 117