2017-02-19 59 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 

如果還有其他文件需要幫助我解決這個問題,請隨時提問。希望在調用數據時獲得更好的理解,例如我目前遇到的問題。

再次感謝您提前給大家。

編輯

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