![](/img/trans.png)
[英]No route matches {:action=>“edit”, :controller=>“comments”, :article_id=>nil, :id=>nil} for editing comments for article in ruby on rails blog
[英]Rails Comments ID => nil
我有一个评论表,我的用户评论电影。 评论belongs_to :movie
和电影has_many :comments
我的问题是,当我创建新评论时,该字段必须在其中<%= f.text_field :movie_id %>
,如果我删除它,我会得到
No route matches {:action=>"show", :controller=>"movies", :id=>nil}
这是创建新评论的绝对路径http://localhost:3000/movies/:movie_id/comments/new
我已经检查了电影控制器中的操作,什么也看不到。 我也曾在Comments控制器中玩过create动作,但还是一无所获。
在我看来,拥有此字段可能会使用户感到困惑。 有人对此有解决方案吗?
这是我的* comments_controller.rb *
class CommentsController < ApplicationController
# GET /comments
# GET /comments.json
before_filter :load_movie
before_filter :authenticate_user!, only: [:create,:destroy,:edit,:destroy]
...
# GET /comments/new
# GET /comments/new.json
def new
@movie = Movie.find(params[:movie_id])
@comment = @movie.comments.new
@search = Movie.search(params[:q])
respond_to do |format|
format.html # new.html.erb
format.json { render json: @comment }
end
end
# POST /comments
# POST /comments.json
def create
@comment = Comment.new(params[:comment])
@comment.user_id = current_user.id
@search = Movie.search(params[:q])
respond_to do |format|
if @comment.save
@movie = @comment.movie
format.html { redirect_to movie_path(@movie), notice: "Comment created" }
format.json { render json: @comment, status: :created, location: @comment }
else
format.html { render action: "new" }
format.json { render json: @comment.errors, status: :unprocessable_entity }
end
end
end
private
def load_movie
@movie = Movie.find_by_id(params[:movie_id])
end
end
routes.rb
AppName::Application.routes.draw do
resources :comments
resources :movies do
resources :comments, only: [:create,:destroy,:edit,:destroy,:new]
member do
get 'comments'
end
end
end
* _form.html.erb *
<%= form_for(@comment) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.text_field :subject %>
<%= f.text_area :body %>
<%= f.text_field :movie_id %>
</div>
<div class="form-actions">
<%= f.submit "Sumbit Review" %>
</div>
<% end %>
resources :movies do
resources :comments, only: [:create,:destroy,:edit,:destroy,:new]
end
将为您提供以下网址:
../movies/:movie_id/comments/new
删除带有movie_id
text_field
,因为这不安全。
在控制器中创建动作:
@movie = Movie.find(params[:movie_id])
@comment = @movie.comments.new(params[:comment])
@comment.user_id = current_user.id
不确定为什么需要:
member do
get 'comments'
end
形成
使用嵌套资源时,您需要像这样构建表单:
<%= form_for ([@movie, @comment]) do |f| %>
<%= f.some_input %>
<% end %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.