Rails - 在不同的区域显示评论

时间:2013-04-15 21:55:51

标签: ruby-on-rails ruby ruby-on-rails-3 models posts

我试图创建一个允许运动员回应他们的教练训练计划的系统,为此我已经允许教练创建内容,但我正在使用基于博客的系统来创建它......目前页面显示如此

内容标题

内容信息1 ...

内容信息2 ...

内容信息3 ...

注释...

评论1

评论2

评论3

.etc

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

内容标题

内容信息1 ...

评论1

内容信息2 ...

评论2

内容信息3 ...

评论3

.etc

我意识到这可能不是我想要的最好的方式,但它有效(只是dosnt出现在我想要它的地方) 我确实做过创建更多模型的实验,但每次尝试每个帖子运行超过1个评论系统时都会遇到错误。我想知道我是否可以帮助整理这个,或者我可以做的任何方法来使这更容易,或者更好,如果模型可以工作,如果我只是做错了什么?告诉我这是不是足够的信息,并尝试提供更多!三江源

编辑:

我使用的模型是 计划 - 与本周的培训计划一样 教练 - 向骑手输入数据的教练 车手 - 用他们自己的数据评论教练数据。

我不确定哪些文件需要完全正确所以我已经包含了我推送到的{github页面的链接(https://github.com/effectonedesign/coacheasy1),如果还有其他需要的信息,请告诉我!

我喜欢“心灵”所说的但是,我已经做了所有事情已经说过,在我的def show(程序控制器)中它说有一个错误,我继续得到这个消息undefined方法`coaches'为nil:NilClass一切都与他的相同,但我得到的问题,我真的很感激帮助!感谢

1 个答案:

答案 0 :(得分:0)

我可能会为上面的TrainingPlanSection(或内容,text_block等)和Comment创建3个模型。

然后执行以下操作

  • TrainingPlan has_many:sections
  • Section belongs_to:training_plan
  • 部分has_one:评论(如果每个部分只允许1条评论,否则请使用has_many)
  • 评论belongs_to: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

在您的视图中查看/ 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 %>

视图/评论/ _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| %>

如果是我,我会通过JavaScript创建添加评论部分,有点像this railscast,但是因为你是RoR的新手,我试图保持简单。