【问题标题】:best way to rewrite /profiles/1/edit/details towards /me/profile/details?将 /profiles/1/edit/details 重写为 /me/profile/details 的最佳方法?
【发布时间】:2013-09-19 05:44:50
【问题描述】:

我试图在“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 原则很不利。我怎样才能以更好的方式实现想要的结果?

【问题讨论】:

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


    【解决方案1】:

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

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

    因此,您将编辑页面称为profile_edit_path(:what => "details")

    结合更多关于您的代码的内容。

    • 你应该把update_attributes改成update
    • 您不应该使用重定向 :back,因为它会呈现一个 js 反向链接而不执行实际请求,因此您不会看到实际更改
    • 您应该将render action => 更改为render :template =>
    • 除非您使用strong_params,否则您不应在更新声明中使用params[:profile]。您需要指定表单允许的参数。这样做是为了防止大规模分配。

    觉得你真的应该看看CodeSchool tutorial on Rails 4

    【讨论】:

    • 很棒的帖子感谢您指出 codeschool rails 4 教程,非常有用。除了升级手册之外,还没有阅读 Rails 4 的细节
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多