I am attempting to add the ability for users to add comments to posts on my rails site.
I have a Posts table and a Users table in my database. I'm using resourceful routes to display individual posts on the 'show' action of my Posts controller. I want to be able to have a comment box show up under the post that the user can enter a comment into, then click submit and have it create the comment.
I tried making a model for comments, giving them a belongs_to relationship for both user and post. I also added the has_many relationship to the user and post models. I then tried to have a Comment Controller use a 'create' action in order to process a form on each posts' 'show' action.
I am running into the issue of not being able to get the post_id to inject into the new comment. I can get the user_id by grabbing it from the user's session, but the only thing passed to the 'create' action on the Comments Controller is the actual text of the comment through the form.
Is this a good way of going about adding this feature? There must be a better way of doing it, or maybe I'm just missing something.
My Posts Controller 'show' action:
#PostsController.rb
def show
@post = Post.where(:id => params[:id]).first
if @post.nil?
flash[:error] = "Post does not exist"
redirect_to(root_path)
end
@comment = Comment.new
end
The form on the 'show' view for the 'show' action on PostsController:
#views/posts/show.html.erb
<%= form_for @comment do |f| %>
<%= f.text_area(:content, :size => '20x10', :class => 'textarea') %>
<%= f.submit('Create Post', class: 'button button-primary') %>
<% end %>
My Comments Controller 'create' action:
#CommentsController.rb
def create
@comment = Comment.new(params.require(:comment).permit(:content, :post_id, :user_id))
@comment.user_id = session[:user_id]
#Need to set post_id here somehow
if @comment.valid?
@comment.save
flash[:success] = "Comment added successfully."
redirect_to(post_path(@comment.post))
else
@error = @comment.errors.full_messages.to_s
@error.delete! '[]'
flash.now[:error] = @error
render('posts/show')
end
end
My Post model:
class Post < ApplicationRecord
belongs_to :subject
belongs_to :user
has_many :comments
validates :title, :presence => true,
:length => {:within => 4..75}
validates :content, :presence => true,
:length => {:within => 20..1000}
end
My Comment model:
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
validates :content, :presence => true,
:length => {:within => 6..200}
end
@post = Post.where(:id => params[:id]).first>>>> you can use.findwith ID, .find - tkhuynh