【问题标题】:ROR: Adding comments to post issueROR:添加评论以发布问题
【发布时间】:2017-02-17 14:28:22
【问题描述】:

我目前正在学习 Rails,但在尝试添加评论时遇到了问题。 如果用户 A 进入用户 B 的帖子下,则评论将显示在用户 A 的所有帖子下,而不是用户 B 的特定帖子下。

我认为问题与视图页面有关,而不是与评论如何保存到数据库有关。

comment.rb

class Comment < ApplicationRecord
 belongs_to :user
 belongs_to :pin
end

cmets.controller.rb

class CommentsController < ApplicationController

 before_action :set_pin

 def create  
    @comment = @pin.user.comments.build(comment_params)
    @comment.user_id = current_user.id

    if @comment.save
    redirect_to root_path
    else
        render root_path
    end
 end

 private

 def comment_params  
   params.require(:comment).permit(:content)
 end

 def set_pin  
  @pin = Pin.find(params[:pin_id])
 end 
end 

index.html.erb

    - if pin.user.comments
                    - pin.user.comments.each do |comment|
                        .commentContainer
                            %h4.desc
                                %strong
                                    =link_to (pin.user.Username), user_path(pin.user_id)
                                = comment.content   

关于如何解决这个问题的任何想法?

编辑。

评论表:

0|id|INTEGER|1||1
1|user_id|integer|0||0
2|pin_id|integer|0||0
3|content|text|0||0
4|created_at|datetime|1||0
5|updated_at|datetime|1||0

sqlite> select * from comments;
1|15||Nice shot!|2017-02-07 16:13:06.707372|2017-02-07 16:13:06.707372
2|15||Cool pic|2017-02-07 16:25:27.780830|2017-02-07 16:25:27.780830
3|14||test|2017-02-08 14:08:17.397782|2017-02-08 14:08:17.397782

【问题讨论】:

    标签: ruby-on-rails ruby model-view-controller


    【解决方案1】:

    我相信你是对的,问题只是你如何显示它们。

    您想从显示 cmets 中删除用户。您要做的是显示属于 pin 的 cmets 列表,然后通过它访问用户的数据。

    - if pin.comments
      - pin.comments.each do |comment|
          .commentContainer
          %h4.desc
          %strong
             =link_to (comment.user.Username),user_path(comment.user.user_id)
          = comment.content 
    

    线

    - pin.comments.each do |comment|
    

    将显示属于该引脚的所有 cmets,无论用户如何。然后你通过它与里面的评论的关系来访问用户的数据。

    (comment.user.Username)
    

    还要确保所有的关系都是双向的。

    Pin.rb

    has_many :comments
    

    用户.rb

    has_many :comments
    

    【讨论】:

    • 当我尝试得到一个未定义的方法错误:undefined method cmets for #<0x9560868>
    猜你喜欢
    • 2016-04-17
    • 2014-10-28
    • 1970-01-01
    • 2012-10-11
    • 2016-10-24
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    • 2011-10-11
    相关资源
    最近更新 更多