Reputation: 231
I have a comments table and my Users comment on a movie. A comment belongs_to :movie
and a movie has_many :comments
My problem is that when I create a new comment, this field has to be there <%= f.text_field :movie_id %>
, and if I remove it, I get
No route matches {:action=>"show", :controller=>"movies", :id=>nil}
This is the absolute path to create a new comment http://localhost:3000/movies/:movie_id/comments/new
I've checked the action in the movies controller and can't see anything. I've also played with the create action in the Comments controller but still nothing.
Having this field in my view can be quite confusing to the user. Does anyone have a solution for this?
This is my *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 %>
Upvotes: 0
Views: 161
Reputation: 11421
resources :movies do
resources :comments, only: [:create,:destroy,:edit,:destroy,:new]
end
will give you url like:
../movies/:movie_id/comments/new
remove that text_field
with movie_id
as this is not safe.
in controller create action:
@movie = Movie.find(params[:movie_id])
@comment = @movie.comments.new(params[:comment])
@comment.user_id = current_user.id
not sure why you need:
member do
get 'comments'
end
Form
when using nested resource you'll need to build you form like this:
<%= form_for ([@movie, @comment]) do |f| %>
<%= f.some_input %>
<% end %>
Upvotes: 1