Reputation:
I created a blog in which users can create comments under posts. Registered users, Admins and Guests will be able to post comments.
So in the _form.html.erb I wrote this:
<%= simple_form_for([@post, @post.comments.build], html: {class: 'form-horizontal' }) do |f| %>
<% if current_user || current_admin %>
<% @comment.commenter = current_user.try(:email) || current_admin.try(:email) %>
<% else %>
<%= f.input :commenter %>
<% end %>
<%= f.input :body %>
<%= f.button :submit %>
<% end %>
However I get this error: undefined local variable or method `comment'.
When I try to change @comment.commenter to @post.comments I get the error: undefined method `each' for "[email protected]":String.
Is there a way set the commenter's name if its registered. Like in the controller maybe?
The controller code is:
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comments_params)
redirect_to post_path(@post)
end
def destroy
@post = Post.find(params[:post_id])
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def comments_params
params.require(:comment).permit(:commenter, :body)
end
end
If you need any other information please let me know.
Thanks
Upvotes: 0
Views: 55
Reputation:
Found a solution:
Controller:
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(comments_params)
if current_admin || current_user
@comment.commenter = current_user.try(:email) || current_admin.try(:email)
@comment.save
end
redirect_to post_path(@post)
end
View:
<%= simple_form_for([@post, @post.comments.build], html: {class: 'form-horizontal' }) do |f| %>
<% if current_admin || current_user %>
<%= f.input :body %>
<% else %>
<%= f.input :commenter %>
<%= f.input :body %>
<% end %>
<%= f.button :submit %>
<% end %>
Thanks for the help.
Upvotes: 0
Reputation: 768
<%= simple_form_for(@comment),url: [@post,@comment], html: {class: 'form-horizontal' }) do |f| %>
<%= f.input :commenter, value: comment_by_user %>
<%= f.input :body %>
<%= f.button :submit %>
Helper
def comment_by_user
current_user.try(:email) || current_admin.try(:email) if current_user || current_admin
end
Controller
class CommentsController < ApplicationController
before_filter :find_post
def new
@comment = @post.comments.build
end
def create
@comment = @post.comments.create(comments_params)
redirect_to post_path(@post)
end
def destroy
@comment = @post.comments.find(params[:id])
@comment.destroy
redirect_to post_path(@post)
end
private
def find_post
@post = Post.find(params[:post_id])
end
end
Upvotes: 1