我正在尝试创建与帖子相关的评论。有3个模型用户,微博和评论。以下是我所拥有的联系:
评语模型
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :micropost
validates :user_id, presence: true
validates :micropost_id, presence: true
end微柱模型
belongs_to :user
has_many :comments, dependent: :destroy用户模型
has_many :microposts, dependent: :destroy
has_many :comments我将路线嵌套为:
resources :microposts do
resources :comments
end这里是我的评论控制器:
class CommentsController < ApplicationController
def create
@micropost = Micropost.find(params[:micropost_id])
@comment = @micropost.comments.build(params[:comment])
if @comment.save
flash[:success] = "Comment created"
redirect_to current_user
else
render 'shared/_comment_form'
end
end
end评论表格:
<%= form_for([@micropost, @comment]) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :content, placeholder: "Write your message.." %>
</div>
<%= f.submit "Post", class: "btn btn-primary" %>
<% end %>当我运行这个时,我得到了一个形式,我得到了一个参数错误,
形式的第一个参数不能包含零或为空
我想知道如何解决这个问题?如果我只写微博,@注释,它似乎也不认识它,我得到了一个未定义的局部变量错误。为什么评论形式没有意识到微博是从评论控制器找到micropost_id?
发布于 2014-11-03 18:29:29
让我们首先了解这个表单是如何工作的。
例如,如果您的资源定义了关联,则如果路由设置正确,则希望向微博添加注释:
<%= form_for([@micropost, @comment]) do |f| %>
...
<% end %>在呈现表单之前定义了@micropost和@comment。
示例:@micropost = Micropost.find(params[:id])和@comment = Comment.new
稍后,当您提交此表单(仅在该步骤上)时,您的create操作将从您的注释控制器中被触及。
因此,基本上,您需要做的是在调用@micropost和@comment之前定义form_for
https://stackoverflow.com/questions/26719765
复制相似问题