ruby-on-rails - 将/profiles/1/edit/details 重写为/me/profile/details 的最佳方法?

标签 ruby-on-rails routing namespaces rewrite ruby-on-rails-4

我试图在“me”/me 部分下命名多个路由,以便在此命名空间下拥有所有基于用户配置文件/帐户的内容,以实现更干净的路由。

解决这个问题的最佳方法是什么?我发现重写默认的 REST 路由(profiles/1/edit)会出现一些问题,比如表单不更新。

路线

get "/me/profile"              => "profiles#show", :as => :my_profile
get "/me/profile/:what"        => "profiles#edit", :as => :my_profile_edit
post "/me/profile/:what"       => "profiles#edit"

ProfilesController
def edit
  @profile      = current_user.profile
  if ["basics", "location", "details", "photos"].member?(params[:what])
    render :action => "edit/edit_#{params[:what]}"
  else
    render :action => "edit/edit_basics"
  end
end

def update
  @profile        = current_user.profile
  @profile.form   = params[:form]
  respond_to do |format|
    if @profile.update_attributes!(params[:profile])
      format.html { redirect_to :back, :notice => t('notice.saved') }
    else
      format.html { render action => "/me/profile/" + @profile.form }
    end
  end
end

如果感觉上面对 REST 原则非常不利。我怎样才能以更好的方式实现想要的结果?

最佳答案

好吧,如果您真的很想坚持使用 REST,我建议您移动 :what进入 GET params 哈希。然后你可以像这样重写你的路线

scope "/me" do
  resource :profile, :only => [:show, :edit, :update]

因此,您将编辑页面命名为 profile_edit_path(:what => "details")
关于您的代码的更多信息。
  • 你应该换 update_attributesupdate
  • 你不应该使用重定向:back,因为它会呈现一个 js 返回链接而不是执行实际请求,所以你不会看到实际的变化
  • 你应该换 render action =>render :template =>
  • 你不应该使用 params[:profile]在您的更新语句中,除非您使用 strong_params。您需要指定从表单中允许哪些参数。这样做是为了防止大规模分配。

  • 认为您真的应该查看 CodeSchool tutorial on Rails 4 .

    关于ruby-on-rails - 将/profiles/1/edit/details 重写为/me/profile/details 的最佳方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804918/

    相关文章:

    ruby - 向 Ruby 类添加的方法在 MiniTest 中抛出 NoMethodError

    mysql - 基于HABTM匹配的Rails查询

    python - 在 URLConf 中定义嵌套 namespace ,用于反转 Django URL——有人有令人信服的例子吗?

    c# - using 指令究竟做了什么?

    Angular 6 nebular 6在组件中获取查询参数

    php - 如何防止 Controller 和操作出现在 cakephp 的 URL 中?

    javascript - 使用 "/"作为 Url 中参数的可选分隔符 - Angular-Ui-Router

    ruby-on-rails - Rails ActiveRecord id 的最大可能值

    ruby-on-rails - 使用带有 accepts_nested_attributes_for 的 Rails 模型

    ruby-on-rails - rails : how do you access belongs_to fields in a view?