我正在开发一个允许用户评论单个“作品”的应用程序(想想博客文章)。模型中的关联如下:
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
在评论表中,一条记录具有以下字段:
id 内容
user_id
created_at
updated_at
work_id
在我的评论控制器中,我有以下创建操作:
def create
@work = Work.find(params[:id])
@comment = @work.comments.create(params[:comment])
@comment.user = current_user
if @comment.save
#flash[:success] = "Post created!"
redirect_to root_url
else
render 'activities'
end
end
我正在尝试将用户和作品与评论相关联,但是当我尝试创建评论时收到以下错误消息:
Unknown action
The action 'update' could not be found for CommentsController
我正在尝试使用以下 StackOverflow 答案作为指南,但该解决方案不适用于我: Rails 3 中单个记录的多个外键?
编辑: 我有一个关于作品#show 操作的添加评论表单:
def show
@work = Work.find(params[:id])
@comment = current_user.comments.create(params[:comment])
@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
评论表单本身:
<%= 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 %>
我在 Comments 控制器上也有一个更新方法:
def update
@comment = current_user.comments.find(params[:id])
if @comment.update_attributes(params[:comment])
flash[:success] = "Comment updated"
redirect_to @comment
end
end