我无法确定我不想嵌套的路线。
我有以下路线:
resources :foos
resources :bars
resources :bazs do
resources :hellos
resources :worlds
end
foo、bar 和 baz 模型都属于用户模型。我不想嵌套另一个层,但我确实想在我的 url 中添加一个与用户的永久链接属性相对应的前缀(类似于每个以用户名为前缀的 github 存储库)。因此,我在所有控制器上都有一个 before 过滤器
def get_scope
@user = User.find_by_permalink(params[:permalink])
end
修改了 to_param 感谢 @cowboycoded
class User < ActiveRecord::Base
def to_param
permalink
end
end
我将这些路由包裹起来
scope ":permalink", :as => :user do
#nested routes here
end
现在只要我将 @user 传递给每个非索引路由,一切都会正常工作。当它已经确定了作用域时,必须返回到我的所有视图并将 (@foo) 替换为 (@user, @foo) 似乎并不很干燥。
除非我弄错了,否则 to_param 方法只是替换 :id ,以便 /users/:id 等 url 显示为 users/permalink 而不是 users/1。我尝试在我的范围内使用这个 :id ,但它与 foo 的 :id 参数冲突并破坏了一切。也许与我缺少的路径有联系?
感谢您提出的任何建议!
I am having trouble scoping routes that I don't want to nest.
I have the following routes:
resources :foos
resources :bars
resources :bazs do
resources :hellos
resources :worlds
end
The foo, bar, and baz models all belong_to a user model. I don't want to nest another layer, but I do want to have a prefix in my url that corresponds to a user's permalink attribute (similar to each github repo prefixed by a username). So I have a before filter on all of my controllers
def get_scope
@user = User.find_by_permalink(params[:permalink])
end
Modified to_param thanks to @cowboycoded
class User < ActiveRecord::Base
def to_param
permalink
end
end
I wrapped those routes with
scope ":permalink", :as => :user do
#nested routes here
end
Now everything works fine as long as I pass @user to every non-index route. It doesn't seem very dry to have to go back to all of my views and replace (@foo) with (@user, @foo) when it is already scoped.
Unless I am mistaken, the to_param method simply replaces :id so that urls such as /users/:id appear as users/permalink instead of users/1. I attempted to use this :id in my scope, but it conflicts with foo's :id param and breaks everything. Maybe there is a connection to paths that I am missing?
Thanks for any suggestions that you may have!
发布评论
评论(1)
您是否尝试过在模型中使用 to_param 方法?这将允许您覆盖默认值并使用 id 以外的其他内容,并将与 URL 帮助程序一起使用
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param
文档中的示例:
我不确定这在范围内的效果如何,因为我还没有尝试过,但我想值得一试。
Have you tried using the to_param method in your model? This will allow you to override the default and use something other than id, and will work with the URL helpers
http://api.rubyonrails.org/classes/ActiveRecord/Base.html#method-i-to_param
Example from documentation:
I'm not sure how well this plays with scope, since I haven't tried it, but I guess its worth a shot.