我可能会为上述创建 3 个模型TrainingPlan
,Section
(或内容、text_block 等)和Comment
.
然后执行以下操作
- TrainingPlan has_many :sections
- 部分 belongs_to :training_plan
- Section has_one :comment (如果每个部分只允许 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
在你看来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 %>
意见/评论/_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 创建添加评论部分,有点像在这个 railscast中,但由于你是 RoR 的新手,我试图让它保持简单。