Ruby on rails 4 表单中的第一个参数在第3行不能包含nil或为空
关于这个问题,我读了很多书,但我不明白为什么它不会像我这样工作。我正在我的帖子控制器中实例化我的新帖子。我使用的是rails 4。那有关系吗 这是我的控制器Ruby on rails 4 表单中的第一个参数在第3行不能包含nil或为空,ruby-on-rails-4,Ruby On Rails 4,关于这个问题,我读了很多书,但我不明白为什么它不会像我这样工作。我正在我的帖子控制器中实例化我的新帖子。我使用的是rails 4。那有关系吗 这是我的控制器 class PostsController < ApplicationController def index @posts = Post.all end def show @post = Post.find(params[:id]) end def new @pos
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to posts_path, :notice => "Your post was saved"
else
render ="new"
end
end
private
def post_params
params.require(:post).permit(:title, :content)
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
redirect_to Posts_path, :notice => "Your post has been updated"
else
render "edit"
end
end
def destroy
end
end
class PostsController“您的帖子已保存”
其他的
render=“新建”
结束
结束
私有的
def post_参数
参数require(:post).permit(:title,:content)
结束
定义编辑
@post=post.find(参数[:id])
结束
def更新
@post=post.find(参数[:id])
如果@post.update_属性(post_参数)
重定向到帖子路径:注意=>“你的帖子已经更新”
其他的
渲染“编辑”
结束
结束
def销毁
结束
结束
下面是我的edit.html.erb中的内容
<h1>Edit Post</h1>
<%= form_for @post do |f| %>
<p>
<%= f.label :title %> <br/>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :content %> <br/>
<%= f.text_area :content %>
</p>
<p>
<%= f.submit "Update Post" %>
</p>
<% end %>
编辑帖子
为什么会说我的@post为零?
我试着做了“form|u for Post.new do | f |”,这很管用。但我听说这不是一个好办法
提前感谢各位。您已将
编辑
、更新
和销毁
操作声明为私有
。由于在呈现特定视图时不会调用这些操作,因此未设置@post
变量。因此,您得到了错误。将其从“专用”部分中删除,并将其添加为“公用”
PostsController
应如下所示:
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new
end
def create
@post = Post.new(post_params)
if @post.save
redirect_to posts_path, :notice => "Your post was saved"
else
render ="new"
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
if @post.update_attributes(post_params)
redirect_to Posts_path, :notice => "Your post has been updated"
else
render "edit"
end
end
def destroy
## You would need the below code for deleting a post
@post = Post.find(params[:id])
@post.destroy
redirect_to roles_url
end
private
def post_params
params.require(:post).permit(:title, :content)
end
end
class PostsController“您的帖子已保存”
其他的
render=“新建”
结束
结束
定义编辑
@post=post.find(参数[:id])
结束
def更新
@post=post.find(参数[:id])
如果@post.update_属性(post_参数)
重定向到帖子路径:注意=>“你的帖子已经更新”
其他的
渲染“编辑”
结束
结束
def销毁
##您需要以下代码来删除帖子
@post=post.find(参数[:id])
@事后销毁
将\u重定向到角色\u url
结束
私有的
def post_参数
参数require(:post).permit(:title,:content)
结束
结束
太棒了!我不敢相信这有多容易。这总是容易的事