1
我正在研究一個應用程序,允許用戶評論一個「工作」(認爲博客文章)。在模型中的關聯如下:未知動作:找不到行動'創建'CommentsController
class User < ActiveRecord::Base
has_many :works
has_many :comments
class Work < ActiveRecord::Base
belongs_to :user
has_many :comments
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :post
belongs_to :work
有對作品形式顯示頁面,使用戶可以發表評論:
<%= form_for(@comment) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Post a comment!" %>
</div>
<%= f.submit "Post", class: "btn btn-small btn-primary" %>
<% end %>
的作品控制器如下。請注意,我在這裏將構建註釋功能,以便在工程頁函數的形式:
class WorksController < ApplicationController
#before_filter :current_user, only: [:edit, :update]
def index
@works = Work.all
@comment = @work.comments.build(params[:comment])
@comment.user = current_user
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @works }
end
end
def create
@work = current_user.works.create(params[:work])
redirect_to current_user
end
def edit
@work = current_user.works.find(params[:id])
end
def new
@work = current_user.works.new
end
def destroy
@work = current_user.works.find(params[:id]).destroy
flash[:success] = "Work deleted"
redirect_to current_user
end
def update
@work = current_user.works.find(params[:id])
if @work.update_attributes(params[:work])
flash[:success] = "Profile updated"
redirect_to @work
else
render 'edit'
end
end
def show
@work = Work.find(params[:id])
@comment = @work.comments.build
@comment.user = current_user
@activities = PublicActivity::Activity.order("created_at DESC").where(trackable_type: "Work", trackable_id: @work).all
@comments = @work.comments.order("created_at DESC").where(work_id: @work).all
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @work }
end
end
end
最後,這裏是評論控制器:
class CommentsController < ApplicationController
before_filter :authenticate_user!
def index
@comments = Comment.all
end
def show
@comment = Comment.find(params[:id])
@activities = PublicActivity::Activity.order("created_at DESC").where(trackable_type: "Comment", trackable_id: @comment).all
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @comment }
end
def update
@comment = current_user.comments.find(params[:id])
if @comment.update_attributes(params[:comment])
flash[:success] = "Comment updated"
redirect_to @comment
end
end
def create
@work = Work.find(params[:id])
@comment = @work.comments.build(params[:comment])
@comment.user = current_user
if @comment.save
#flash[:success] = "Post created!"
redirect_to @work
else
render 'home#index'
end
end
end
end
當我嘗試提交使用的作品評論表單評論顯示視圖頁上,我得到以下錯誤:
未知的動作 「創造」的操作無法找到CommentsController
爲什麼它不能在評論控制器上找到創建操作?任何幫助將不勝感激。
謝謝!
+1使得代碼的縮進一致將直接顯示問題。 – sevenseacat
非常感謝你的回覆。我肯定從這個菜鳥的錯誤中學到了東西!我收到一個新的錯誤(無法找到沒有ID的工作),但這解決了我發佈的問題。我越來越近了! – winston