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