我的問題是,如何調用指定給創建評論的特定帖子的評論+用戶信息。例如:需要幫助調用數據庫中的某些評論
/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
你能分享評論的模式嗎? – MZaragoza
@MZaragoza添加了我的模式。 –
,你想要8後的所有評論? – MZaragoza