如何让控制器通过if-else语句呈现不同的形式?

时间:2015-04-19 16:45:45

标签: ruby-on-rails ruby-on-rails-4

我正在尝试重新配置我的密码重置功能,以便我可以将它用于其他型号。除了一个问题,我已经完成了所有工作。

能够通过搜索两个表来找到用户。然后它会发送http://url/password_resets/Uhhi7Omp***pigTtg/edit?email=main%40example.com等链接。

但是它应该呈现不同的形式,具体取决于用户来自哪个表。在我刚刚控制的控制器中:

def edit
end

但我现在有两个视图,一个用于每种类型的用户/表。我在控制器中尝试了以下内容:

  def edit
    if @type1                  #This if statement works, also use it for other methods in the controller.
      render _to edit_type1    #Name of the view file
    elsif @type2
      render reset_type1       #Name of the view file
    end
  end

但是由于edit_type1和type2对于路由是未知的,所以这不起作用。我应该在路线文件中添加什么?由于视图没有自己的控制器方法,我不确定。

路线:

resources :password_resets,     only: [:new, :create, :edit, :update]

2 个答案:

答案 0 :(得分:0)

这与路由无关 - 它将请求分派给正确的控制器和操作,因此其工作已完成(直到您需要生成更多URL)

这应该只是

render action: "edit_type1"

答案 1 :(得分:0)

如果您想创建其他路线,可以

resources:password_resets do
  member do
    get 'edit_type_1', to: 'my_controller#type_1_incoming, as: 'edit_type1'
    get 'edit_type_2', to: 'my_controller#type_2_incoming, as: 'edit_type2'
  end
end

resources:password_resets do
  collection do
    get 'edit_type_1', to: 'my_controller#type_1_incoming, as: 'edit_type1'
    get 'edit_type_2', to: 'my_controller#type_2_incoming, as: 'edit_type2'
  end
end

membercollection之间的差异,如果您需要传递id来指定特定对象。

...但我认为您不需要根据我的要求修改您的路线。您想显示不同的表单,但是采用相同的update方法?

然后两种形式应该有这样的......

<%= form_for :password_reset do |f| %>

表单将自动提交给password_resets_controller,update方法。