Rails 嵌套单一资源路由 [英] Rails Nested Singular Resource Routing

查看:45
本文介绍了Rails 嵌套单一资源路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的 User 模型和一个单一的嵌套 Profile 资源,所以在我的 routes.rb 中我有:

I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

resources :users do
  resource :profile, :only => [:edit, :update, :show]
end

这会生成预期的路由:

edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}

我创建了一个简单的控制器更新方法来更新模型,然后在成功更新后重定向:

I've created a simple controller update method that updates the model and then redirects upon successful update:

def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end

问题是提交表单后,表单会重定向到 mydomain.com/users/4/profile.22,其中 22 恰好是配置文件的 ID.显然,这会混淆控制器,因为路由将22"解释为格式.

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile. Clearly this confuses the controllers since the routing interprets the '22' as the format.

我的问题是,我如何让它重定向到 mydomain.com/users/4/profile?我已经尝试了 redirect_to 语句的以下变体,但没有效果,它们全部导致相同的错误网址:

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead? I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )

此外,在其他地方使用 'user_profile_path(@user)' 会产生正确的 url.

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

有什么想法吗?哦,如果有帮助的话,我正在使用 Rails 3.0.0 和 Ruby 1.9.2.

Any ideas? Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.

推荐答案

环顾四周,似乎生成更新的表单的 url 不正确.如果有人看到这个问题,那是因为我的表单设置为:

After looking around, it appears that the form generating the update had an incorrect url. If anyone is seeing this issue, it's because I had my form set up as:

form_for [@user, @profile] do |f| ...

这导致表单操作的 url 不正确(上面有问题的表单).相反,我使用了

This caused the form action to have the incorrect url (of the offending form above). Instead, I used

form_for @profile, :url => user_profile_path(@user) do |f| ...

一切似乎都奏效了.

这篇关于Rails 嵌套单一资源路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆