【发布时间】:2013-08-19 18:20:31
【问题描述】:
我正在尝试创建一个包含用户、帖子和 cmets 的博客。每个用户可以有很多帖子和很多 cmets,同样每个帖子可以有很多 cmets。我已成功创建用户和帖子部分,但在创建 cmets 并显示它们时遇到了困难。
代码:
routes.rb:
resources :users do
resources :posts do
resources :comments
end
end
用户.rb:
has_many :posts, dependent: :destroy
has_many :comments, dependent: :destroy
post.rb:
belongs_to :user
has_many :comments, dependent: :destroy
comment.rb:
belongs_to :post, :user
我正在帖子的视图中创建和显示 cmets 所以..
posts_controller.rb:
def show
@user = current_user
@post = Post.find(params[:id])
end
查看/posts/show.html.erb:
<p><strong>Title:</strong><%= @post.title %></p>
<p><strong>Text:</strong><%= @post.text %></p>
<% if @user.posts.comments.empty? %>
<h2>Comments</h2>
<%= render @posts.comments %>
<% end %>
<h2>Add a comment:</h2>
<%= render "comments/form" %>
<%= link_to 'Edit Post', edit_user_post_path(@user.id,@post) %> |
<%= link_to 'Back to Posts', user_posts_path(@user.id) %>
cmets_controller.rb:
class CommentsController < ApplicationController
def create
@user = current_user
@post = @user.posts.find(params[:post_id])
@comment = @user.posts.comments.create(params[:comment])
redirect_to user_post_path(@user.id,@post)
end
def destroy
@user = current_user
@post = @user.posts.find(params[:post_id])
@comment = @user.posts.comments.find(params[:id])
@comment.destroy
redirect_to user_post_path(@user.id,@post)
end
end
部分内容是:
views/cmets/_form.html.erb:
<%= form_for([@user,@post,@comment]) do |f| %>
<p>
<%= @user.email %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
我认为我的 form_for 不在这里,但我是 Rails 新手,我也尝试过 form_for(@user,@post,@post.cmets.build) 但这也不起作用..无论如何这里是另一个部分:
views/cmets/_comment.html.erb:
<p><strong>Commenter:</strong><%= @user.email %></p>
<p><strong>Comment:</strong><%= comment.body %></p>
<p><%= link_to 'Destroy Comment', [comment.post, comment],method: :delete,
data: { confirm: 'Are you sure?' } %>
</p>
再次在这里,我无法链接到...任何建议都会很棒。
【问题讨论】:
-
运行 rake 路由并将输出粘贴到 gist 或 paste.org
-
@rmagnum2002 这是 rake 路由列表link
标签: ruby-on-rails ruby-on-rails-3 comments nested-routes