0

我有一个评论表,我的用户对一部电影发表评论。一条评论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

路线.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 %>
4

1 回答 1

1
resources :movies do
  resources :comments, only: [:create,:destroy,:edit,:destroy,:new]
end

会给你像这样的网址:

../movies/:movie_id/comments/new

删除它text_fieldmovie_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 %>
于 2013-08-12T22:43:26.317 回答