Ruby on Rails中控制器和操作中定义的路径被忽略 [英] Path defined in controller and action is getting ignored, Ruby on Rails
问题描述
根据 http://guides.rubyonrails.org/layouts_and_rendering.html
我应该能够像在micropostscontroller中的create动作中那样定义来自其他控制器的路径:
I should be able to define the path from a different controller as I have done in my create action in my 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
时,重定向有效.为什么浏览器会忽略渲染请求并转到微博控制器的主页?
When I unsuccessfully create a post, however (leave it blank or make it too long), the page '/microposts' is rendered, the nonexistent home page of the controller. When I successfully create a micropost I am redirected to the profile path '/profile', and when I've changed render 'static_pages/profile'
to redirect_to profile_path
the redirect works. Why is the browser ignoring the render request and going to the microposts controller home?
此外,呈现的微博页面还提供了NoMethodError:
Additionally, the rendered microposts page gives a 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])
The profile renders fine on its own when when redirected to, as @user is defined in profile action in the static_pages controller. @user = User.find_by_remember_token(cookies[:remember_token])
推荐答案
您的create方法正在尝试呈现"app/views/static_pages/profile.html.erb",但您尚未为其指定@user来呈现.如果您以此方式修改代码,它应该可以工作:
Your create method is attempting to render 'app/views/static_pages/profile.html.erb', but you haven't given it a @user to render. If you revise your code this way it should work:
def create
@micropost = current_user.microposts.build(params[:micropost])
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to profile_path
else
@user = current_user # Add this line!
render 'static_pages/profile'
end
end
请注意,microposts#create
方法的路径为/microposts
,因此除非您使用redirect_to
而不是render
,否则它仍将显示在地址栏中.
Note that the path of the microposts#create
method is /microposts
, so that will still show in your address bar unless you use redirect_to
instead of render
.
这篇关于Ruby on Rails中控制器和操作中定义的路径被忽略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!