gpt4 book ai didi

ruby-on-rails - 为资源(单数)和资源(复数)创建 Rails 路线的最佳方法?

转载 作者:行者123 更新时间:2023-12-04 05:52:22 26 4
gpt4 key购买 nike

我有一个 profile我的应用程序中的模型。我想允许用户通过 /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_path不传递配置文件/ID 参数,这意味着每当我需要链接到那里时,我都必须使用字符串“/配置文件”。
$ 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

您的 Profile模型
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 是一个模型,你

关于ruby-on-rails - 为资源(单数)和资源(复数)创建 Rails 路线的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5926192/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com