Vasseurth
Vasseurth

Reputation: 6486

How do I create relationships and associations for a User Model of Devise

I am using devise for my user model and in the routes.rb I have devise_for :users How would I go about giving users posts?

Would it just be in the routes:

resources :users do
    resources :posts
end

Or do you have to do something special due to devise

Upvotes: 2

Views: 2604

Answers (1)

Gazler
Gazler

Reputation: 84150

Those routes will work, additionally you need to set up your relationships in your models, assuming your posts table includes user_id as a foreign key:

class User < ActiveRecord::Base
  has_many :posts
  has_many :comments
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :comments
end

class Comments < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

edit

To add the foreign key to your Post model:

rails g migration add_user_id_to_posts user_id:integer

This will create a migration file in the db/migrate folder that looks like:

class AddUserIdToPosts < ActiveRecord::Migration
  def self.up
    add_column :posts, :user_id, :integer
  end

  def self.down
    remove_column :posts, :user_id
  end
end

You can then migrate these changes to your database using: rake db:migrate

Upvotes: 6

Related Questions