我的路线看起来像这样
resources :questions do
resources :answers do
resources :comments
end
end
然而,当我尝试建立评论时
<%= form_for([@answer, @answer.comments.build]) do |f| %>
<p>
<%= f.label :comment %>
<%= f.text_area :comment, :cols => "50", :rows => "30"%>
</p>
<p>
我得到未定义的方法注释。这就是我的创建评论看起来像
def create
@answer = Answer.find(params[:answer_id])
@comment = @answer.comments.create(params[:comment])
redirect_to question_path(@question)
end
回答has_many评论,评论属于答案。有任何想法吗?谢谢!
答案 0 :(得分:0)
您可以从应用中的任何控制器访问模型(只需拨打Model.class_method
)
查看您的代码,我建议您这样做:
#app/views/answers/show.html.erb
<% @answer.comments.each do |comment| %>
<%= comment.value %>
<% end %>
<%= form_for @new_comment do |f| %>
<%= f.text_area :comment, :cols => "50", :rows => "30"%>
<% end %>
#app/controllers/answers_controller.rb
def new
@answer = Answer.find(params[:id])
@new_comment = Comment.new
end
#app/controllers/comments_controller.rb
def create
@comment = Comment.new(comment_params)
@comment.save
end
private
def comment_params
params.require(:comment).permit(:your, :attributes, :here)
end