我有一個照片共享網路應用程式,我正在嘗試在照片中添加評論。我找不到任何錯誤。也許在索引函式的控制器類中是問題所在。當我嘗試在照片下方顯示評論時出現未定義方法錯誤。HAML 代碼錯誤。
錯誤:-如果@photo_comments.any?
控制器:
class CommentsController < ApplicationController
def index
@photo_comments = Comment.where(photo_id: => photo_id)
end
def create
@comment = Comment.create(user_id: params[:user_id], photo_id: params[:photo_id], text: params[:comment][:text])
flash[:notice] = "Successfully added a comment"
redirect_to :back
end
private
def comment_params
params.require(:comment).permit(:user_id, :photo_id, :text)
end
end
模型:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :photo
end
資料庫:
class CreateComments < ActiveRecord::Migration
def change
create_table :comments do |t|
t.integer :user_id
t.integer :photo_id
t.string :text
t.timestamps
end
end
end
看法:
%p Comments
- if @photo_comments.any?
- @photo_comments.each do |comment|
.bold-text= "#{comment.user.email}: "
.normal-text= comment.text
%br
- else
.text No comments for this photo yet!
%br
%br
%p
= form_for Comment.new(), :url => user_photo_comments_path do |form|
= form.label :text, 'Add a Comment'
%br
= form.text_area :text
%br
= form.submit 'Post'
路線:
Rails.application.routes.draw do
get '/' => 'home#index'
resources :users do
resources :photos do
resources :comments
end
resources :follows
end
resources :tags, only: [:create, :destroy]
get '/log-in' => "sessions#new"
post '/log-in' => "sessions#create"
get '/log-out' => "sessions#destroy", as: :log_out
end
uj5u.com熱心網友回復:
這兩行沒有意義:
- if @photo_comments.nil?
- @photo_comments.each do |comment|
如果實體變數@photo_comments是nil那么迭代呢?當然,undefined method 'each' for nil:NilClass在那種情況下你會得到一個。
我猜你的意思是這樣的:
- unless @photo_comments.nil?
- @photo_comments.each do |comment|
uj5u.com熱心網友回復:
這條線似乎有點問題:
@photo_comments = Comment.where(photo_id: => photo_id)
我可以在這里發現幾個潛在的錯誤:
- 哈希語法:你混合了兩種風格,你應該使用
photo_id: photo_idor (Ruby pre 1.9):photo_id => photo_id - 該方法或變數
photo_id似乎未在該控制器中定義,也許您的意思是params[:photo_id]?
uj5u.com熱心網友回復:
這行肯定有語法錯誤:
@photo_comments = Comment.where(photo_id: => photo_id)
也photo_id沒有在控制器的任何地方定義,所以也許它應該看起來像:
@photo_comments = Comment.where(photo_id: params[:photo_id])
?
undefined_method在對值呼叫方法時經常會出現錯誤nil。在您的情況下,實體變數@photo_comments為 nil,因此在視圖中給您帶來 undefined_method 錯誤。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536867.html
