【问题标题】:How to express this route in Rails?如何在 Rails 中表达这条路线?
【发布时间】:2012-03-08 19:49:58
【问题描述】:

我似乎无法从我的嵌套控制器访问显示操作。我能够创建一个对象,但 redirect_to 失败。

routes.rb

 blog_topic_posts POST   /blog/topics/:topic_id/posts(.:format)  blog/posts#create
 edit_blog_topic_post GET    /blog/topics/:topic_id/posts/:id/edit(.:format) blog/posts#edit
 blog_topic_post GET    /blog/topics/:topic_id/posts/:id(.:format)      blog/posts#show
 PUT    /blog/topics/:topic_id/posts/:id(.:format)      blog/posts#update
 DELETE /blog/topics/:topic_id/posts/:id(.:format)      blog/posts#destroy

创建动作:

def new
 @post = Post.new 
 @tag = @post.tags.build
end

def create
 @post = Post.new(params[:post])
 @post.user = current_user
  respond_to do |format|
   if @post.save
    flash[:success] = 'Post was successfully created.'
    format.html { redirect_to([:blog, @topic, @post]) }
   else
    format.html { render action: :new }
   end
  end
 end

当我通过上述重定向时,它会返回路由错误:

  NoMethodError in Blog::PostsController#create

  undefined method `blog_post_url' for #<Blog::PostsController:0x00000002ee34f8>

  {"utf8"=>"✓",
   "authenticity_token"=>"dN9feAsRVJal9P1YDtgEeHHwsP4yr3rZT1KBjgR57SI=",
   "post"=>{"title"=>"ban",
   "description"=>"bobobo",
   "content"=>"---- sequi- molestias- qui- veritatis- quasi- modi- praesentium- nesciunt- voluptates- exercitationem",
   "topic_id"=>"1",
   "tags_attributes"=>{"0"=>{"tag_name"=>"bank"}}},
   "commit"=>"Create Post"}

谁能解释为什么这条路线会失败?为什么它不寻找 blog_topic_post_url?顺便说一句,同一控制器中的以下重定向适用于 PUT...

def update
 # loading in post object via before_filter
 if @post.update_attributes(params[:post])
  flash[:success] = "Post was successfully updated."
  redirect_to blog_topic_post_url([@post.topic]) 
 else
  flash[:error] = "Post could not be saved."
  render :edit 
 end
end

【问题讨论】:

  • 你的 routes.rb 文件显示了什么?
  • @WaynnLue 请查看路线,文件。我决定使用来自 create 的传统重定向,现在我收到了上面的错误。
  • 想通了。需要这样表示的路线redirect_to([:blog, @post.topic]) 不是这样redirect_to([:blog, @topic, @post])
  • 啊,有道理。您应该使用该代码回答您的问题并接受它。 :)

标签: ruby-on-rails routes nested-forms


【解决方案1】:

路由函数when:

redirect_to([:blog, @post.topic]) 

但不是这样:

redirect_to([:blog, @topic, @post])

这与update 操作相同。我现在不需要在创建帖子对象时加载@topic,因为它已经在帖子对象中设置了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2011-04-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    • 2022-01-06
    相关资源
    最近更新 更多