【问题标题】:Rails: How to redirect to a specific controller (index) depending on conditionRails:如何根据条件重定向到特定的控制器(索引)
【发布时间】:2021-12-09 20:51:37
【问题描述】:

我有一个 Ruby on Rails 应用程序,它可以为电影中的演员生成“角色”;这个想法是,如果用户查看电影详细信息页面,他们可以单击“添加角色”,如果他们查看演员详细信息页面也是如此。 生成角色后,我想重定向回它们的来源 - 电影详细信息页面或演员详细信息页面......所以在控制器的“创建”和“更新”方法中,redirect_to 应该是 movie_path( id) 或 actor_path(id)。我如何保持“原点”持久,即。 e.我如何记住用户是来自电影详细信息还是演员详细信息(分别是 id)?

【问题讨论】:

  • 您可以使用request.referer 了解触发add role 操作的位置并将其存储在会话对象中或将其添加为表单中的隐藏字段。然后,当提交 for 时,您可以检查会话或参数中的隐藏字段,以了解返回到哪里
  • 好主意,很简单。在我敢于下面更复杂的解决方案之前,可能会尝试这个! :)

标签: ruby-on-rails


【解决方案1】:

我会设置单独的嵌套路由并只使用继承、混合和部分以避免重复:

resources :movies do
  resources :roles, module: :movies, only: :create
end

resources :actors do
  resources :roles, module: :actors, only: :create
end
class RolesController < ApplicationController 
  before_action :set_parent

  def create
    @role = @parent.roles.create(role_params)
    if @role.save 
      redirect_to @parent
    else
      render :new
    end
  end

  private 

  # guesses the name based on the module nesting
  # assumes that you are using Rails 6+ 
  # see https://stackoverflow.com/questions/133357/how-do-you-find-the-namespace-module-name-programmatically-in-ruby-on-rails
  def parent_class
    module_parent.name.singularize.constantize
  end

  def set_parent
    parent_class.find(param_key)
  end

  def param_key
    parent_class.model_name.param_key + "_id"
  end

  def role_params
    params.require(:role)
          .permit(:foo, :bar, :baz)
  end
end
module Movies
  class RolesController < ::RolesController
  end
end
module Actors
  class RolesController < ::RolesController
  end
end
# roles/_form.html.erb
<%= form_with(model: [parent, role]) do |form| %>
  # ...
<% end %>

【讨论】:

  • 哇,太棒了,我才意识到 Rails 中有多少东西......我还有多少 csn 学习!谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-15
  • 2012-01-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多