我有一个评论表,我的用户对电影发表评论。评论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_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 %>
答案 0 :(得分:1)
resources :movies do
resources :comments, only: [:create,:destroy,:edit,:destroy,:new]
end
会给你网址:
../movies/:movie_id/comments/new
将text_field
移除movie_id
,因为这不安全。
在控制器创建动作中:
@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 %>