我想你看我只是想在每篇文章的展示页面上发表评论,我也在使用Friendly_id。问题是我无法通过使用来自评论控制器的slug找到该文章,我不确定问题出在哪里。
{0}
class CommentsController < ApplicationController def create @article = Article.friendly.find(params[:slug]) @comment = @article.comments.create(comments_params) redirect_to @article_path(@article) end private def comments_params params.require(:comment).permit(:name, :body) end end
comment form
class ArticlesController < ApplicationController before_filter :authenticate_user!, except: [:index, :show] def index @Articles = Article.all end def new @article = Article.new end def create @article = Article.new(article_params) if @article.save redirect_to @article else render 'new' end end def show find_article end def edit find_article end def update @article = Article.find_by_slug(params[:id]) if @article.update(article_params) redirect_to @article else render 'edit' end end def destroy @article = Article.find(params[:id]) @article.destroy redirect_to root_path end private def find_article @article = Article.friendly.find(params[:id]) end def article_params params.require(:article).permit(:title, :content, :slug) end end
comment
<%= form_for ([@article, @article.comments.build]) do |f| %> <%= f.label :Name %> <%= f.text_field :Name %> <br> <%= f.label :Body %> <%= f.text_area :Body %> <br> <%= f.submit %> <% end %>
Article Model
<p><%= comment.content %><p/>
Comment Model
class Article < ActiveRecord::Base has_many :comments extend FriendlyId friendly_id :title, use: [:slugged, :finders] end
Routes
class Comment < ActiveRecord::Base belongs_to :article end
答案 0 :(得分:0)
我想它应该是这样的:
class CommentsController < ApplicationController
def create
@article = Article.friendly.find(params[:article_id])
@comment = @article.comments.create(comments_params)
redirect_to article_path(@article)
end
private
def comments_params
params.require(:comment).permit(:name, :body)
end
end