Ok, am still a newbie in ruby on rails trying to learn my way around. I have two models (User model and Comment model). Basically a user has a simple profile with an 'about me' section and a photo's section on the same page. Users must be signed in to comment on other users profiles.
My User Model
class User < ActiveRecord::Base
attr_accessible :email, :name, :username, :gender, :password, :password_confirmation
has_secure_password
has_many :comments
.
.
end
My Comment Model
class Comment < ActiveRecord::Base
belongs_to :user
attr_accessible :content
.
.
end
In my comments table, I have a user_id
column that stores the id of the user whose profile has been commented on and a commenter_id
column that stores the id of the user commenting on the profile.
Comment Form
<%= form_for([@user, @user.comments.build]) do |f| %>
<%= f.text_area :content, cols: "45", rows: "3", class: "btn-block comment-box" %>
<%= f.submit "Comment", class: "btn" %>
<% end %>
My comments Controller
class CommentsController < ApplicationController
def create
@user = User.find(params[:user_id])
@comment = @user.comments.build(params[:comment])
@comment.commenter_id = current_user.id
if @comment.save
.........
else
.........
end
end
end
This works fine storing both user_id
and commenter_id
in the database. My problem comes when displaying the user comments on the show page. I want to get the name of the user who commented on a specific profile.
In my user controller
def show
@user = User.find(params[:id])
@comments = @user.comments
end
I want to get the name of the user from the commenter_id
but it keeps throwing errors undefined method 'commenter' for #<Comment:0x007f32b8c37430>
when I try something like comment.commenter.name
. However, comment.user.name
works fine but it doesn't return what I want. Am guessing am not getting the associations right.
I need help getting the correct associations in the models so as to get the name from the commenter_id.
My last question, how do I catch errors in the comments form? Its not the usual form_for(@user)
where you do like @user.errors.any?
.
routes.rb
resources :users do
resources :comments, only: [:create, :destroy]
end