我的问题是,如何调用指定给创建评论的特定帖子的评论+用户信息。例如:需要帮助调用数据库中的某些评论
/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