我正在嘗試添加用戶添加評論到我的rails站點上的帖子的能力。我如何評論我的帖子?
我在我的數據庫中有一個Posts表和一個Users表。我正在使用足智多謀的路線在我的帖子控制器的'show'動作上顯示各個帖子。我希望能夠在帖子下方顯示評論框,以便用戶輸入評論,然後點擊提交併讓它創建評論。
我試着做一個評論模型,給他們一個belongs_to關係的用戶和帖子。我還將has_many關係添加到用戶和發佈模型。然後,我嘗試讓評論控制器使用「創建」操作來處理每個帖子「顯示」操作的表單。
我遇到了無法獲取post_id以注入新評論的問題。我可以通過從用戶會話中獲取user_id來獲取user_id,但傳遞給評論控制器上的「創建」操作的唯一內容就是通過表單評論的實際文本。
這是添加此功能的好方法嗎?必須有更好的做法,或者我只是想念一些東西。
我的帖子控制器「秀」行動:
#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
在「顯示」視圖的形式在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 %>
我的意見控制器「創建」行動:
#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
我的Post模型:
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
我的評論模式:
class Comment < ApplicationRecord
belongs_to :user
belongs_to :post
validates :content, :presence => true,
:length => {:within => 6..200}
end
您是否正在學習任何教程?請更新您的問題與帖子和評論模型 – Hizqeel
你到達那裏,這並不難,嘗試深入挖掘在線資源,你會發現它很容易。順便說一句,'@post = Post.where(:id => params [:id])。first' >>>>你可以使用'.find'與ID,[.find](http:// apidock。 com/rails/ActiveRecord/FinderMethods/find) – tkhuynh
@Hizqeel我在Lynda上使用了一個關於我的初始應用程序創建的教程,但是我無法在線找到有關如何添加註釋的資源。我爲我的模型添加了代碼。 – Kecoey