问题
I am trying to redirect to the show action after a successful create action in order to see the post the user just made (Post controller). I am getting this error message:
syntax error, unexpected keyword_ensure, expecting end-of-input
More debugging info: unless source.valid_encoding? raise WrongEncodingError.new(@source, Encoding.default_internal) end
begin
mod.module_eval(source, identifier, 0)
ObjectSpace.define_finalizer(self, Finalizer[method_name, mod])
rescue => e # errors from template code
if logger = (view && view.logger)
logger.debug "ERROR: compiling #{method_name} RAISED #{e}"
logger.debug "Function body: #{source}"
Here is the Post Controller
class PostsController < ApplicationController
def index
@posts = Post.all
end
def show
@post = Post.find(params[:id])
end
def new
@post = Post.new(params[:id])
end
def create
@post = Post.new(params[:id])
if @post.save
redirect_to @post
else
render :new
end
end
end
Here is my show view:
<h1>Posts</h1>
Title: <%= post.title %><br>
Body: <%= post.body %><br>
url: <%= post.url %><br>
<% end %>
index view:
<% @posts.each do |post| %>
Thanks for your help. I can't find the answer anywhere else.
回答1:
SHOW view must be:
<h1>Post</h1>
Title: <%= @post.title %><br>
Body: <%= @post.body %><br>
INDEX view must be:
<h1>Posts</h1>
<% @posts.each do |post| %>
Title: <%= post.title %><br>
Body: <%= post.body %><br>
<% end %>
Also change create action to such:
def create
@post = Post.new(post_params)
if @post.save
redirect_to @post
else
render :new
end
end
And add to controller (before last end
):
private
def post_params
params.require(:post).permit(:title, :body, :url) #here you put all attributes you want be able to assign when creating the post
end
回答2:
You don't pass id
of new object which is required for action show
redirect_to post_path(@post)
or according to guides.rubyonrails.org (see chapter "4 Parameters") you can write
if @post.save
redirect_to @post
else
render :new
end
来源:https://stackoverflow.com/questions/25376395/i-am-trying-to-redirect-to-the-show-actionso-i-can-see-the-new-post-if-a-save