当我点击“新帖子:
”时,这是我遇到的错误表单中的第一个参数不能包含nil或为空
我的PostController:
class PostsController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@posts = Post.all
end
def show
end
def edit
end
def update
@post.update(post_params)
redirect_to posts_path
end
def new
if user_signed_in?
@post = Post.new
else
flash[:alert] = ":("
end
end
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
@post.save
redirect_to posts_path
end
def destroy
if user_signed_in?
@post.destroy!
else
flash[:alert] = ":("
end
redirect_to posts_path
end
private
def post_params
params.require(:post).permit(:body)
end
def set_user
@post = Post.find(params[:id])
end
端
和帖子#index:
<% @posts.each do |post| %>
<%= post.body %>
<%= link_to 'Show', post %>
<%= link_to 'Edit', edit_post_path(post) %>
<%= link_to 'Delete', post, method: :delete %>
<br>
_form.html.erb
<%= form_for(@post) do |f| %>
<div class="field">
<%= f.label :body %><br>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
答案 0 :(得分:0)
您应该检查“new.html.erb”或“_form.html.erb”文件。查看是否正确调用了“form_for”方法。
答案 1 :(得分:0)
如果您正在使用设计,可以通过添加之前的操作来实现此目的:
before_action :authenticate_user!, only: [:new]
你的新动作:
def new
@post = Post.new
end