Rails3 路由错误

发布于 2024-12-21 07:02:32 字数 1090 浏览 2 评论 0原文

我的场景:电影有评论,评论有评论。

电影模型:

has_many :reviews

评论模型:

has_many :comments
belongs_to :movie

评论模型:

belongs_to :review

路线:

resources :movies do
  resources :reviews do
    resources :comments
  end
end

评论控制器:

def create
  @movie = Movie.find(params[:movie_id])
  @review = Review.where(:movie_id => @movie.id)
  @comment = @review.comments.create(params[:comment])  // Line 5
  redirect_to movie_path(@movie)
end

评论视图:

<%= form_for([@movie, r, r.comments.build]) do |f| %>
  <div class="field">
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>

我得到的错误是:

NoMethodError (undefined method `comments' for #<ActiveRecord::Relation:0x007ff5c5870010>):
app/controllers/comments_controller.rb:5:in `create'

有人可以告诉我我做错了什么吗?

提前致谢..

My scenario: Movies have reviews, reviews have comments.

Movie model:

has_many :reviews

Review model:

has_many :comments
belongs_to :movie

Comment model:

belongs_to :review

Routes:

resources :movies do
  resources :reviews do
    resources :comments
  end
end

Comments controller:

def create
  @movie = Movie.find(params[:movie_id])
  @review = Review.where(:movie_id => @movie.id)
  @comment = @review.comments.create(params[:comment])  // Line 5
  redirect_to movie_path(@movie)
end

Comment view:

<%= form_for([@movie, r, r.comments.build]) do |f| %>
  <div class="field">
    <%= f.text_area :body %>
  </div>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
<% end %>

The error that I get is:

NoMethodError (undefined method `comments' for #<ActiveRecord::Relation:0x007ff5c5870010>):
app/controllers/comments_controller.rb:5:in `create'

Can somebody please tell me what I'm doing wrong?

Thanks in advance..

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

所有深爱都是秘密 2024-12-28 07:02:32

Review.where 返回评论列表,您想要的是一个实例

@review = Review.where(:movie_id => @movie.id).first

@review = Review.find_by_movie_id(@movie.id)

确保处理 nil 情况。

Review.where returns a list of reviews, what you want is an instance

@review = Review.where(:movie_id => @movie.id).first

or

@review = Review.find_by_movie_id(@movie.id)

Make sure to handle nil case.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文