Ruby on rails 轨道。视野中的错误
我有后置控制器,我用的是像样的曝光宝石Ruby on rails 轨道。视野中的错误,ruby-on-rails,devise,Ruby On Rails,Devise,我有后置控制器,我用的是像样的曝光宝石 #posts_controller.rb class PostsController < ApplicationController expose(:posts) { Post.all } expose(:post) do Post.find(params[:id]) || Post.new end def create post = current_user.posts.new(params[:post])
#posts_controller.rb
class PostsController < ApplicationController
expose(:posts) { Post.all }
expose(:post) do
Post.find(params[:id]) || Post.new
end
def create
post = current_user.posts.new(params[:post])
if post.save
redirect_to post, notice: 'Post was successfully created.'
else
render action: :new
end
end
def update
if post.update_attributes(params[:post])
redirect_to post, notice: 'Post was successfully updated.'
else
render action: "edit"
end
end
def destroy
post.destroy
redirect_to posts_url, notice: "Post was deleted."
end
end
为什么?尝试替换:
Post.find(params[:id]) || Post.new
与:
常见的模式是检查是否提供了ID 您通常还应该使用
posts.find
和posts.build
而不是Post.find
和Post.new
expose(:post) { (id = params[:id]) ? posts.find(id) : posts.build }
非常感谢。但是,现在,当我输入了错误的数据,没有显示验证错误时,我删除了我的答案,因为这是正确的答案。请注意,当您尝试使用nil作为参数调用
#find
时,会调用此错误,在您的情况下,它是参数[:id]
。
Couldn't find Post without an ID
Post.find(params[:id]) || Post.new
Post.find_by_id(params[:id]) || Post.new
expose(:post) { (id = params[:id]) ? posts.find(id) : posts.build }