【发布时间】:2016-06-28 22:45:50
【问题描述】:
我就像你看到的那样,我只是想在每篇文章显示页面上都有 cmets,我也在使用 Friendly_id。问题是我无法通过使用 Comments 控制器中的 slug 找到该文章,而且我不确定问题出在哪里。
评论控制器
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
文章控制器
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
意见表
<%= 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 %>
评论
<p><%= comment.content %><p/>
文章模型
class Article < ActiveRecord::Base
has_many :comments
extend FriendlyId
friendly_id :title, use: [:slugged, :finders]
end
评论模型
class Comment < ActiveRecord::Base
belongs_to :article
end
路线
Rails.application.routes.draw do
devise_for :users
root 'articles#index'
resources :articles do
resources :comments
end
end
【问题讨论】:
-
您能发布
Article和Comment模型的代码吗? -
@mqngo 他们现在在那里 :)
-
你能分享你的 routes.rb 吗?
-
我看不出代码有什么问题。您是否使用
rails console来验证Comment是否正确附加到Article?我看到你有来自create函数CommentController的params[:slug],但在permit子句中没有接受它。你是从routes收到的吗? -
这是 Rails 控制台输出 2.3.1 :004 > article = Article.find(1) Article Load (1.9ms) SELECT "articles".* FROM "articles" WHERE "articles"."身份证”=? LIMIT 1 [["id", 1]] => #
标签: ruby-on-rails ruby-on-rails-4 activerecord rails-activerecord friendly-id