为多个模型引用的嵌套资源生成编辑路径
在routes.rb中:
resources :cars do
resources :reviews
end
resources :motorcycles do
resources :reviews
end
在ReviewsController中:
before_filter :find_parent
def show
@review = Review.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @review }
end
end
def edit
@review = Review.find(params[:id])
end
# ...
def find_parent
@parent = nil
if params[:car_id]
@parent = Car.find(params[:car_id])
elsif params[:motorcycle_id]
@parent = Motorcycle.find(params[:motorcycle_id])
end
end
生成评论的“显示”链接很简单(这有效):
= link_to "Show", [@parent, @review]
同样,我想引用评论的通用编辑路径,例如(这不起作用):
= link_to "Edit", [@parent, @review], :action => 'edit'
有谁知道如果这可能,或者如果不可能,如何实现?
In routes.rb:
resources :cars do
resources :reviews
end
resources :motorcycles do
resources :reviews
end
In ReviewsController:
before_filter :find_parent
def show
@review = Review.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @review }
end
end
def edit
@review = Review.find(params[:id])
end
# ...
def find_parent
@parent = nil
if params[:car_id]
@parent = Car.find(params[:car_id])
elsif params[:motorcycle_id]
@parent = Motorcycle.find(params[:motorcycle_id])
end
end
Generating the "show" link for a Review is simply (this works):
= link_to "Show", [@parent, @review]
Similarly I would like to reference a generic edit path for a Review, something like (this does not work):
= link_to "Edit", [@parent, @review], :action => 'edit'
Does anyone know if this is possible or, if not, how this might be accomplished?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
事实证明,我正在寻找的答案可以通过 URL 帮助程序“edit_polymorphic_path”找到(请参阅: http://rubydoc.info/github/rails/rails/master/ActionDispatch/Routing/PolymorphicRoutes)。为了获得我在上面尝试的链接,我能够通过以下方式完成此操作:
It turns out the answer I am looking for can be found with the URL helper "edit_polymorphic_path" (see: http://rubydoc.info/github/rails/rails/master/ActionDispatch/Routing/PolymorphicRoutes). In order to get the link I am attempting above I was able to accomplish this with:
我认为你在这里需要的是多态关联。 Railscasts.com 的 Ryan Bates 对此进行了完美的解释。
http://railscasts.com/episodes/154-polymorphic-association
它会成功您可以轻松拥有以下内容:
用户、管理员、注释
用户可以有许多注释
一个经理可以有很多笔记
注释可以属于用户或管理员
users/1/notes/edit
manager/1/notes/edit
Railscast 将解释如何执行此操作:)
编辑:
然后在您的链接中,它会类似于:
^^ 未测试。
I think what you need here is a polymorphic assocation. Ryan Bates at Railscasts.com explains it perfectly.
http://railscasts.com/episodes/154-polymorphic-association
It will make it easy for you to have things like:
User, Manager, Note
A user can have many notes
A manager can have many notes
A note can belong to a user OR a manager
users/1/notes/edit
managers/1/notes/edit
The Railscast will explain how to do it :)
EDIT:
Then in your link to, it would be something like:
^^ Not tested.