如何调用注释+为在其下创建注释的特定帖子指定的用户信息。例如:
/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 %>
我获取与评论相关的用户信息,但问题是,它列出了所有评论。例如,如何仅使用article_id为8进行注释。
后置控制器
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 :(得分: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 %>
我希望这应该有效。