【发布时间】:2015-05-16 02:09:07
【问题描述】:
在设计中使用 Rails 4
我有一个 Post 模型和一个 Comment 模型。评论嵌套在帖子中。我已将帖子分配给用户,但由于它是嵌套的,因此无法将 cmet 分配给用户。
routes.rb
resources :posts do
resources :comments
end
用户.rb
has_many :posts
has_many :comments
post.rb:
has_many :comments
belongs_to :user
comment.rb:
belongs_to :post
belongs_to :user
在我的 cmets_controller.rb 中,我尝试过像这样使用 current_user:
def new
post = Post.find(params[:post_id]
@comment = current_user.post.comments.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @comment }
end
end
def create
post = Post.find(params[:post_id])
@comment = current_user.post.comments.create(comment_params)
respond_to do |format|
if @comment.save
format.html { redirect_to(@comment.post, :notice => 'Comment was successfully created.') }
format.xml { render :xml => @comment, :status => :created, :location => [@comment.post, @comment] }
else
format.html { render :action => "new" }
format.xml { render :xml => @comment.errors, :status => :unprocessable_entity }
end
end
end
但我收到此错误:
undefined method `post' for #<User:0x00000103300a30>
解决此问题的最佳方法是什么?
【问题讨论】:
-
不应该是帖子
标签: ruby-on-rails ruby ruby-on-rails-4 devise