I have a Photo Share web app and I am trying to add comments in photos. I can't spot any mistakes. Maybe in the controller class in index function is the problem. There is an undefined method error when I try to show-post comments below the photo. Error in HAML code.
Error: - if @photo_comments.any?
Controller:
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
Model:
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :photo
end
Database:
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
View:
%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'
Routes:
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
This line seems a bit problematic:
@photo_comments = Comment.where(photo_id: => photo_id)
I can spot a couple of potential errors here:
photo_id: photo_id
or (Ruby pre 1.9) :photo_id => photo_id
photo_id
seems not defined in that controller, maybe you would mean params[:photo_id]
?