ruby-on-rails – 为资源(单数)和资源(复数)创建Rails路由的最佳
发布时间:2020-12-17 02:10:53 所属栏目:百科 来源:网络整理
导读:我的应用程序中有一个配置文件模型.我想允许用户通过/ profile查看自己的个人资料,所以我创建了这个路线: resource :profile,:only = :show 我还希望用户能够通过/ profiles / joeblow查看其他用户的个人资料,所以我创建了这条路线: resources :profiles,:
我的应用程序中有一个配置文件模型.我想允许用户通过/ profile查看自己的个人资料,所以我创建了这个路线:
resource :profile,:only => :show 我还希望用户能够通过/ profiles / joeblow查看其他用户的个人资料,所以我创建了这条路线: resources :profiles,:only => :show 问题是,在第二种情况下,有一个:id参数,我想用它来查找配置文件.在第一种情况下,我只想使用登录用户的个人资料. 这就是我用来找到正确的配置文件,但我想知道是否有更合适的方法可以做到这一点. class ProfilesController < ApplicationController before_filter :authenticate_profile! before_filter :find_profile def show end private def find_profile @profile = params[:id] ? Profile.find_by_name(params[:id]) : current_profile end end 编辑:此方法的一个问题是我的路线.我不可能在不传递profile / ID参数的情况下调用profile_path,这意味着每当我需要链接时,我都必须使用字符串’/ profile’. $rake routes | grep profile profile GET /profiles/:id(.:format) {:action=>"show",:controller=>"profiles"} GET /profile(.:format) {:action=>"show",:controller=>"profiles"} 解决方法
你的路线:
resource :profile,:only => :show,:as => :current_profile,:type => :current_profile resources :profiles,:only => :show 然后你的ProfilesController class ProfilesController < ApplicationController before_filter :authenticate_profile! before_filter :find_profile def show end private def find_profile @profile = params[:type] ? Profile.find(params[:id]) : current_profile end end 您的个人资料模型 class Profile < AR::Base def to_param name end end 浏览次数: <%= link_to "Your profile",current_profile_path %> <%= link_to "#{@profile.name}'s profile",@profile %> # or <%= link_to "#{@profile.name}'s profile",profile_path( @profile ) %> 另外:如果Profile是模特,你 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |