在不同的控制器中设计表单 [英] Devise form within a different controller

查看:23
本文介绍了在不同的控制器中设计表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为 sign_in/sign_out 程序使用设计 gem.

I am using a devise gem for sign_in/sign_out procedures.

我从设计生成视图文件,使用 rails g devise views

I generated views files from devise, using rails g devise views

我看到有一个 devise/sessions/new.html.erb 文件,其中包含一个登录表单.

I saw there was a devise/sessions/new.html.erb file which contained a form for sign_in.

我创建了另一个文件 devise/sessions/_form.html.erb 并在 new.html.erb 文件中做了 <%= render 'form' %> ,结果非常好很好.

I created another file devise/sessions/_form.html.erb and did <%= render 'form' %> within a new.html.erb file, and that worked out very fine.

现在,我想从不同的控制器中包含这个表单.因此,在名为main"的控制器中(特别是在视图页面中)mains/index.html.erb",我包含了 <%= render 'devise/sessions/form' %> 文件.似乎包含工作正常,但我收到以下错误.

Now, I wanted to include this form from the different controller. So in a controller called 'main', (specifically, within view page) 'mains/index.html.erb' I included <%= render 'devise/sessions/form' %> file. It seems that inclusion worked fine, but I am getting the following error.

NameError in Mains#index

Showing /home/administrator/Ruby/site_v4_ruby/app/views/devise/sessions/_form.html.erb where line #1 raised:

undefined local variable or method `resource' for #<#<Class:0x007f1aa042d530>:0x007f1aa042b870>
Extracted source (around line #1):

1: <%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
2:   <p><%= f.label :email %><br />
3:   <%= f.text_field :email %></p>
4: 

似乎是 form_for(resource,...) 部分导致了问题(如果我在原始设计 sign_in 页面上工作正常......我如何以 rails 方式解决这个问题?

It seems that form_for(resource,...) part is causing the problem (which works fine if I am on the original devise sign_in page... How can I resolve this problem in rails way?

我个人更喜欢使用 'render' 函数来包含表单,而不是内联编写 html 代码.

I personally prefer to use 'render' function to include the form, rather than writing html codes inline.

我是否必须在主"控制器中指定某些内容(资源)?

Do I have to specify something (resource) within the 'main' controller?

感谢您的帮助.谢谢.

推荐答案

正如 Andres 所说,表单调用由 Devise 指定的助手,因此当您从非 Devise 控制器访问 Devise 表单时,这些助手不存在.

As Andres says, the form calls helpers which are specified by Devise and so aren't present when you access a Devise form from a non-Devise controller.

为了解决这个问题,您需要将以下方法添加到您希望在其下显示表单的控制器的帮助程序类中.或者,您可以将它们添加到您的应用助手中,以便在任何地方使用它们.

To get around this, you need to add the following methods to the helper class of the controller you wish to display the form under. Alternatively, you can just add them to your application helper to make them available anywhere.

  def resource_name
    :user
  end

  def resource
    @resource ||= User.new
  end

  def devise_mapping
    @devise_mapping ||= Devise.mappings[:user]
  end

来源:http://pupeno.com/blog/show-a-devise-log-in-form-in-another-page/

这篇关于在不同的控制器中设计表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆