2011-07-13 9 views

答えて

5

これらのルートは動作します考案による特別な何かをしなければならないの、さらにあなたのモデルでは、あなたの関係を設定する必要がありますあなたの投稿を仮定しての表は、外部キーとしてuser_idは含まれています

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 

編集

あなたPostモデルへの外部キーを追加するには:あなたは、これらの変更を移行することができます

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

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

:ように見える。この移行/ DBに移行ファイルを作成するフォルダ

rails g migration add_user_id_to_posts user_id:integer 

を rake db:migrate

+0

どのようにuser_idを外部キーとして追加しますか? – Vasseurth

+1

@Planetpluto:私の編集を参照してください。これにより、user.postsやpost.userなどのメソッドを使用できるようになります – Gazler

+0

また、私はコメントのために正確なsmaeを行うこともできますか? しかし、投稿をコメント – Vasseurth

関連する問題