点击创建评论后,我收到了这样的错误
控制员:
` 我使用了FriendlyId而不是post id。
错误:
class CommentsController< ApplicationController中
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create(params[:comment].permit(:name, :body))
redirect_to post_path(@post)
end
comments form: _comments.html.erb
`<%= form_for([@post,@post.comments.build]) do |f| %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :body %><br>
<%= f.text_area :body %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>`
posts controller: post_controller.rb
`class PostsController < ApplicationController
before_action :set_post, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all.order("created_at DESC")
end
def show
end
def new
@post = Post.new
end
def edit
end
def create
@post = Post.new(post_params)
respond_to do |format|
if @post.save
format.html { redirect_to @post, notice: 'Post was successfully created.' }
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @post.update(post_params)
format.html { redirect_to @post, notice: 'Post was successfully updated.' }
format.json { render :show, status: :ok, location: @post }
else
format.html { render :edit }
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
def destroy
@post.destroy
respond_to do |format|
format.html { redirect_to posts_url, notice: 'Post was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_post
@post = Post.friendly.find(params[:id])
end
def post_params
params.require(:post).permit(:title, :description, :image)
end
end
`
model: post.rb
class Post < ApplicationRecord
has_many :comments
extend FriendlyId
friendly_id :title, use: :slugged
has_attached_file :image, styles: { medium: "900x380#", thumb: "300x165>" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
end
答案 0 :(得分:0)
要做:
@post = Post.friendly.find(params[:post_id])
添加此后,通过运行
将新列添加到数据库表中rails g migration AddSlugToPosts slug:uniq
完成此操作后,找到您的帖子模型并添加:
extend FriendlyId
friendly_id :first_name, use: :slugged
注意:我为{使用first_name
。由您决定使用哪个,您可以阅读更多有关如何设置友好的here的信息。