ruby on rails create profile page



我创建了一个控制器配置文件
现在我在我的 edit.html.erb 和 show.html.erb 中有该代码

<%= form_for @profile do |f| %>
    <%= f.text_field :name %>
    <%= f.submit %>
<% end %>

因此,假设当用户更新表单时,永久链接将是:

profiles/:id/

但基本上我希望永久链接是这样的:

profiles/%username%

我希望它实际上像"我的配置文件"控制器,用户应该只编辑他的配置文件,而用户应该只有配置文件

这真的很容易做到。我假设您在路由文件中使用resources。你只需要告诉 Rails 你想使用 slug 而不是 id 来访问、更新和删除资源。

resources :profiles, param: :slug

现在,您的资源将通过 slug 生成。在您的控制器中,为了访问单个资源,您需要执行以下操作:

Profile.find_by_username(params[:slug])

你的问题让你看起来来自wordpress背景,并没有完全掌握Rails到底是什么,所以如果是这样的话,你可能想对Rails Guide做更多的研究,并找到一些Rails教程来做。但是,要回答您的问题,在您的application_controller.rb中,您可以执行以下操作:

def profile_path(profile, options={})
  profile_url(profile, options.merge(:only_path => true))
end
def profile_url(profile, options={})
  url_for(options.merge(:controller => 'profiles', :action => 'show',
                      :id => profile.username))
end

最新更新