@post.comments.all 很清楚。我发送表格后没有看到任何错误。当我点击“提交”时,我发送到帖子/id/comments,但是
我的路线.rb
resources :posts do
resources :comments
end
后控制器
def show
@current_user ||= User.find(session[:user_id]) if session[:user_id]
@commenter = @current_user
@post = Post.find(params[:id])
@comment = Comment.build_from( @post, @commenter.id, "234234" )
@comments = Comment.all
respond_to do |format|
format.html
format.json { render json: @post }
end
end
评论控制器
class CommentsController < ApplicationController
def index
@comments = @post.comments.all
end
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.new params[:comment]
if @comment.save
redirect_to @post # comment not save, so i dont redirect to this page
else
# is that there
end
end
end
后模型
acts_as_commentable
has_many :comments
评论模型
class Comment < ActiveRecord::Base
acts_as_nested_set :scope => [:commentable_id, :commentable_type]
attr_accessible :commentable, :body, :user_id
validates :body, :presence => true
validates :user, :presence => true
# NOTE: install the acts_as_votable plugin if you
# want user to vote on the quality of comments.
#acts_as_votable
belongs_to :commentable, :polymorphic => true
# NOTE: Comments belong to a user
belongs_to :user
# Helper class method that allows you to build a comment
# by passing a commentable object, a user_id, and comment text
# example in readme
def self.build_from(obj, user_id, comment)
new \
:commentable => obj,
:body => comment,
:user_id => user_id
end
#helper method to check if a comment has children
def has_children?
self.children.any?
end
# Helper class method to lookup all comments assigned
# to all commentable types for a given user.
scope :find_comments_by_user, lambda { |user|
where(:user_id => user.id).order('created_at DESC')
}
# Helper class method to look up all comments for
# commentable class name and commentable id.
scope :find_comments_for_commentable, lambda { |commentable_str, commentable_id|
where(:commentable_type => commentable_str.to_s, :commentable_id => commentable_id).order('created_at DESC')
}
# Helper class method to look up a commentable object
# given the commentable class name and id
def self.find_commentable(commentable_str, commentable_id)
commentable_str.constantize.find(commentable_id)
end
end
发布视图
%h2 Add a comment:
- @comments.each do |c|
= @c.body
= form_for([@post, @comment]) do |f|
.field
= f.label :body
%br/
= f.text_area :body
.actions
= f.submit
在此先感谢,抱歉英语不好