【发布时间】:2012-04-13 01:39:40
【问题描述】:
根据http://guides.rubyonrails.org/layouts_and_rendering.html
我应该能够定义来自不同控制器的路径,就像我在 micropostscontroller 中的创建操作中所做的那样:
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to profile_path
else
render 'static_pages/profile'
end
end
但是,当我未能成功创建帖子时(将其留空或使其过长),页面“/microposts”被渲染,控制器的主页不存在。当我成功创建微博时,我被重定向到配置文件路径“/profile”,当我将render 'static_pages/profile' 更改为redirect_to profile_path 时,重定向工作。为什么浏览器会忽略渲染请求并转到 microposts 控制器主页?
此外,渲染的微博页面会出现 NoMethodError:
NoMethodError in Microposts#create
undefined method `name' for nil:NilClass
<% provide(:title, @user.name) %>
app/views/static_pages/profile.html.erb:16:in `_app_views_static_pages_profile_html_erb___1610169404003779010_70327969935820'
app/controllers/microposts_controller.rb:10:in `create'
配置文件在重定向到时会自行呈现,因为@user 是在 static_pages 控制器的配置文件操作中定义的。 @user = User.find_by_remember_token(cookies[:remember_token])
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 redirect path render