繁体   English   中英

Rails-在其他区域显示评论

[英]Rails - showing comments in a different area

我正在尝试创建一个允许运动员响应其教练训练计划的系统,为此,我允许教练创建内容,但是我正在使用基于博客的系统来创建它……此刻页面显示如下

内容标题

内容信息1 ...

内容信息2 ...

内容信息3 ...

评论...

评论1

评论2

评论3

。等等

但是我想设置它,以便每个帖子最多只能有7条评论以及每个帖子都这样设置...

内容标题

内容信息1 ...

评论1

内容信息2 ...

评论2

内容信息3 ...

评论3

。等等

我意识到这可能不是实现我想要的最好方法,但是它可以正常工作(只是在我想要的地方没有出现)我做了创建更多模型的实验,但是每当我尝试运行更多模型时都会出错每个帖子1个评论系统。 我想知道我是否可以帮助您解决这个问题,或者我可以采取什么方法使事情变得更容易,或者如果模型可以工作并且我做错了什么甚至更好? 告诉我这是否还不够,请尝试提供更多信息! 谢谢

编辑:

我使用的模型是“程序”-如本周训练计划中所设定的-“教练”正在将数据输入到骑手“骑手”中-使用自己的数据对教练数据进行评论。

我不确定确切需要什么文件,因此我已经包含了我要推送到的github页面的链接( https://github.com/effectonedesign/coacheasy1 ),如果需要其他信息,请告诉我!

我喜欢“头脑”所说的,但是我已经做了所有已经说过的事情,在我的def show(程序控制器)中,这是说有错误,并且我一直在为nil:NilClass收到此消息未定义的方法“ coachs”,所有内容都相同对于他的问题,但我遇到了麻烦,我非常感谢您的帮助! 谢谢

我可能会为上述代码创建3个模型, TrainingPlanSection (或内容,text_block等)和Comment

然后执行以下操作

  • TrainingPlan has_many:sections
  • 所属部分:培训计划
  • 部分has_one:comment(如果每个部分只允许1条评论,否则使用has_many)
  • 评论属地:section

现在,要实现所需的格式,请在视图中执行以下操作:

<% @training_plan.sections.each do |section| %>
  <%= section.text %>
  <%= section.comment.text %>
<% end %>

如果您允许多个评论:

<% @training_plan.sections.each do |section| %>
  <%= section.text %>
  <% section.comments.each do |comment| %>
    <%= comment.text %>
  <% end %>
<% end %>

意见表

我尚未测试以下内容,因此您可能需要调整一些部分。
培训计划负责人:

def show
  # using includes will query the database 3 times only (once for each table) rather than
  # querying it 1 + N + N (in this case 7 sections, 7 comments possibly, so 15 times)
  @training_plan = TrainingPlan.includes(:sections, sections: :comment).find(params[:id])
  @sections = @training_plan.sections
  @sections.each do |section|
    # only build a new comment if there is no comment for that section already
    section.build_comment unless section.comment
  end
end

在您的视图中views / training_plans / show.html.erb

<%= @training_plan.title %> # or whatever
<% @sections.each do |section|
  <%= @section.content %>
  <% if section.comment %>
    <%= section.comment.content %>
  <% else %>
    <%= render 'comments/form', comment: section.comment %> # or wherever you have the form
  <% end %>
<% end %>

views / comments / _form.html.erb

# This might break if you have a separate comment action somewhere which passes an
# instance variable @comment to the form
<%= form_for comment do |f| %>
  # normal form stuff
<% end %>

如果所有这些都可行,那么在您的培训计划展示页上,您应该看到每个部分,如果有评论,则将呈现该评论,否则将显示一个表格。

根据您的路线,您可能需要运行rake routes并查看注释创建操作的位置,然后将其传递给<%= form for comment, url: some_url_helper_here do |comment| %> <%= form for comment, url: some_url_helper_here do |comment| %>

如果是我,我会通过JavaScript创建add comment部分,就像在这个railscast中一样,但是由于您是RoR的新手 ,所以我尝试使其保持简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM