所以我试图创建一个表单让用户对电影发表评论,但 Rails 不断向我抛出未定义的方法错误。我的应用程序允许用户查看电影。所以我希望表单允许用户在该电影的上下文中创建评论。我的代码如下,任何帮助将不胜感激。我唯一的困惑是,我不确定是否应该嵌套资源,或者我只是使用为form_for
我的路线文件如下所示:
resources :users
resources :movies
resources :reviews
resources :sessions, only: [:new, :create, :destroy]
我有一个看起来像这样的评论控制器:
class ReviewsController < ApplicationController
def create
movie_id = params[:review].delete(:movie_id)
@review = Review.new(params[:review])
@review.movie_id = movie_id
@review.save
redirect_to movie_path(@review.movie)
end
end
我的表格如下所示:
<h2>Leave a Review</h2>
<%= form_for(@review) do |f| %>
<%= f.hidden_field :movie_id %>
<div class="field">
<%= f.text_area :content, placeholder: "Write a new review..." %>
</div>
<%= f.submit "Submit", class: "btn btn-large btn-primary" %>
<% end %>
我有三个模型:
用户:
class User < ActiveRecord::Base
has_secure_password
has_many :reviews, dependent: :destroy
has_many :movies, through: :reviews
end
电影:
class Movie < ActiveRecord::Base
has_many :reviews
has_many :users, through: :reviews
end
审查:
class Review < ActiveRecord::Base
attr_accessible :content, :movie_id
belongs_to :user
belongs_to :anime
end
这是错误:
NoMethodError in Movies#show
Showing /Users/david/Sites/Rails/Chirp/app/views/movies/show.html.erb where line #32 raised:
undefined method `model_name' for NilClass:Class
Extracted source (around line #32):
29:
30: <h2>Leave a Review</h2>
31:
32: <%= form_for(@review) do |f| %>
33: <%= f.hidden_field :movie_id %>
34: <div class="field">
35: <%= f.text_area :content, placeholder: "Write a new review..." %>