![](/img/trans.png)
[英]Rails Routing Error (undefined local variable or method `micropost_comment')
[英]Rails: Routing Error, comment model to micropost model
我制作了一個評論系統,試圖將其發布到微博下,但我不斷遇到此路由錯誤。 有什么建議么? 非常感謝所有幫助!
Routing Error
No route matches [POST] "/microposts/comments"
形成
<div class="CommentField">
<%= form_for ([@micropost, @micropost.comments.new]) do |f| %>
<%= f.text_area :content, :class => "CommentText", :placeholder => "Write a Comment..." %>
<div class="CommentButtonContainer">
<%= f.submit "Comment", :class => "CommentButton b1" %>
</div>
<% end %>
</div>
評論控制器
class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = @micropost.comments.build(params[:comment])
@comment.user_id = current_user.id
@comment.save
respond_to do |format|
format.html
format.js
end
end
end
路線
resources :microposts do
resources :comments
end
微郵模型
class Micropost < ActiveRecord::Base
attr_accessible :title, :content, :view_count
acts_as_voteable
belongs_to :user
has_many :comments
has_many :views
accepts_nested_attributes_for :comments
end
用戶控制器
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
@school = School.find(params[:id])
@micropost = Micropost.new
@comment = Comment.new
@comment = @micropost.comments.build(params[:comment])
@microposts = @user.microposts.paginate(:per_page => 10, :page => params[:page])
end
end
出現此錯誤的原因是,您正在嘗試為數據庫中尚不存在的micropost
的comments
構建表單。
表格中有-
form_for ([@micropost, @micropost.comments.new]) do |f|
在UsersController中,您可以-
@micropost = Micropost.new
comment是micropost的子資源,因此創建評論的url應該看起來像/micropost/:id/comments
,其中:id是micropost的ID。 只有在保存微職位后才有可能。
因此,我認為您的操作應將@micropost
分配給現有帖子,或在其中創建一個以使表格正常工作。 就像是 -
@micropost = Micropost.last || Micropost.create
至少會消除錯誤。
我將再次嘗試(刪除其他答案,因為正如Marc Talbot所指出的那樣,這不是對您問題的正確答案) 。
也許問題就像將:micropost
改為:microposts
一樣簡單(以反映您模型的名稱) 。
resources :micropost do
resources :comments
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.