簡體   English   中英

Rails評論ID => nil

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM