Rails 3-嵌套资源路由-一对一关系 [英] Rails 3 - Nested Resources Routing - One to One relationship
问题描述
某些嵌套资源路由遇到麻烦。我想做的是链接到用户的个人资料页面以进行编辑。在我看来,它写为:
Having some trouble with some nested resources routing. What I'm trying to do is link to a user's profile page for editing purposes. In my view it is written as:
<%= link_to "Edit Profile", edit_user_profile_path(current_user) %>
出现以下错误:
No route matches {:action=>"edit", :controller=>"profiles", :user_id=>#<User id: 1, email: "EDITEDOUT", hashed_password: "EDITEDOUT", created_at: "2011-01-20 18:30:44", updated_at: "2011-01-20 18:30:44">}
在我的route.rb文件中,看起来像这样:
In my routes.rb file, it looks like so:
resources :users do
resources :profiles, :controller => "profiles"
end
我检查了Rake路线,并将其作为有效选项:
I checked my Rake routes, and it gave me this as a valid option:
edit_user_profile GET /users/:user_id/profiles/:id/edit(.:format) {:action=>"edit", :controller=>"profiles"}
我可以手动设置导航。为了获得良好的效果,这里是我的控制器的证明:
Which I am able to manually navigate to. For good measures, here's proof of my controller:
class ProfilesController < ApplicationController
def edit
@user = current_user
@profile = current_user.profile
end
def update
@user = current_user
@profile = current_user.profile
respond_to do |format|
if @profile.update_attributes(params[:profile])
format.html { redirect_to(orders_path, :notice => "Your profile has been updated.") }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }
end
end
end
end
无论如何,我一直在追踪这个问题。任何指针都会有所帮助。对于我的数据库设计,概要文件以一对一关系属于用户。我希望这只是新事物,我没有注意到新的眼睛可能会有所帮助。
Anyway, I've been having some problem tracking this down. Any pointers would help. For my DB design Profiles belong to Users in a one-to-one relationship. I'm hoping it's just something newbish I'm not noticing a new set of eyes might help.
推荐答案
在您的路线上,您会看到它同时期望:user_id
和:id
。在这种情况下,后者指的是用户个人资料。
If you look closely at your route, you'll see that it expects both a :user_id
and an :id
. The latter, in this case, refers to the user profile.
为了告诉Rails您想要该特定个人资料,您必须同时指定用户和链接中的个人资料,例如:
In order to tell Rails that you want that particular profile, you'll have to specify both the user and the profile in your link, like this:
edit_user_profile_path(current_user, @profile)
现在,Rails将对 current_user
) >:user_id 的一部分,而:id $ c的第二个参数(
@profile
) $ c>。
Now, Rails will use the first argument (current_user
) for the :user_id
part of the route, and the second argument (@profile
) for the :id
.
这篇关于Rails 3-嵌套资源路由-一对一关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!