2017-02-19 2 views
1

私の質問は、コメントが作成された特定の投稿に指定されたコメント+ユーザー情報を呼び出す方法です。たとえば、次のようにデータベースから特定のコメントを呼び出す際に助けが必要です

/articles/8 

new comment created with user_id = 3 

Page will show Username + comment + created_at 

これは私の現在のコードです:私はコメントに関連付けられたユーザ情報をつかむことができるよ、私が書いた何からページ

<%= @post.title %> 
<%= render '/comments/form' %>  
<% @post.user.comments.reverse.each do |comment| %> 
    <li> 
    <%= comment.user.email %> 
    <%= comment.comment %> 
    </li> 
<% end %> 

ポストショー問題は、すべてのコメントを記載していることです。たとえば、8のarticle_idを使ってコメントを出すにはどうすればいいですか?

より多くのコードについて下記をご覧ください。

ポストコントローラー

def create 
@post = Post.new(post_params) 
@post.user = current_user 
if @post.save! 
    flash[:notice] = "Successfully created..." 
    redirect_to posts_path 
else 
    flash[:danger] = "failed to add a post" 
    render 'new'  
end 
end 

def show 
@comment = Comment.new 
@comments = Comment.find(params[:id]) 
end 

コメントコントローラー

def create 
@post = Post.find(params[:post_id]) 
@comment = @post.comments.build(comment_params) 
@comment.user = current_user 

if @comment.save 
    flash[:notice] = "Successfully created..." 
    redirect_to post_path(@post) 
else 
    flash[:alert] = "failed" 
    redirect_to root_path 
end 
end 

ルート

resources :sessions, only: [:new, :create, :destroy] 
resources :users 
resources :posts do 
resources :comments 
end 

この問題を解決するために必要な追加ファイルがある場合は、お気軽にお問い合わせください。現在の問題など、データを呼び出す際の理解を深めることを願っています。

もう一度全員にありがとうございます。

EDIT

create_table "comments", force: :cascade do |t| 
    t.text  "comment" 
    t.integer "user_id" 
    t.integer "post_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    end 
+0

あなたはコメントのスキーマを共有できますか? – MZaragoza

+0

@Mzaragoza私のスキーマを追加しました。 –

+0

と投稿8のすべてのコメントが欲しいですか? – MZaragoza

答えて

1

私は、我々はこの

ような何かを行うことができます私たちは、ポストのためにすべてのコメントを取得したいモデルが

class Comments < ApplicationRecord 
    belongs_to :user 
    belongs_to :post 
end 
class User < ApplicationRecord 
    has_many :posts 
    has_many :comments 
end 
class Post < ApplicationRecord 
    belongs_to :user 
    has_many :comments 
end 

ようになっていることを想定しています

# Note that I took the user from this line 
<% @post.comments.reverse.each do |comment| %> 
    <li> 
    <%= comment.user.email %> 
    <%= comment.comment %> 
    </li> 
<% end %> 

これがうまくいくことを願っています。

+0

は完璧に動作します。ありがとうございました。ちょうど質問。モデルを呼び出していない場合でも、ユーザー情報にはどのようにアクセスしていますか?私たちがアクセスできるように、それはコメントの一部なのですか? –

+0

投稿はユーザーとコメントの両方を持っています。あなたは間違った割り当てを見てどこで – MZaragoza

関連する問題