【问题标题】:Devise controllers rails设计控制器导轨
【发布时间】:2010-12-28 12:15:45
【问题描述】:

我在 ruby​​ 1.8.7 上使用 Rails 3。并用于身份验证。设计(1.1.3)。但这是我正在构建的一个相当大的社区网站,所以我有一个个人资料表和一个用户表。每次用户注册时,它也应该生成一个配置文件,但在设计中我不允许控制器,所以我完全迷路了..

编辑

现在它说

undefined method `getlocal' for Tue, 28 Dec 2010 11:18:55 +0000:DateTime

然后,当我使用此代码在 lib 中创建一个名为 date_time.rb 的文件时

class DateTime
  def getlocal
    "it works"
  end
end

在我的应用程序控制器中需要它,它给了我这个

fail wrong number of arguments (1 for 0)

就像它不再知道任何叫做设计的东西,但在我的路线中我确实有设计

devise_for :users

【问题讨论】:

  • 在设计问题页面上有一条评论提到了“getlocal”错误:github.com/plataformatec/devise/issues/issue/240#issue/240/… 可能记录已损坏 - 也许尝试使用 db:reset 清除数据?
  • 天哪,我简直不敢相信这就是全部......谢谢,非常感谢!
  • 老实说 - 这是一个猜测......但谢谢!
  • 猜不猜,它成功了,现在回到第一个问题。

标签: ruby-on-rails devise controllers


【解决方案1】:

您可以将 Devise RegistrationsController 子类化并在 create() 方法中添加自己的逻辑,并为其他所有内容调用父类方法。

class MyRegistrationsController < Devise::RegistrationsController
  prepend_view_path "app/views/devise"

  def create
    super
    # Generate your profile here
    # ...
  end

  def update
    super
  end
end

如果您想自定义打包在 Gem 中的 Devise 视图,那么您可以运行以下命令为您的应用生成视图文件:

rails generate devise:views

您还需要告诉路由器使用您的新控制器;类似:

devise_for :users, :controllers => { :registrations => "my_registrations" }

【讨论】:

  • 有了这个,我可以把所有的东西都超级,然后自己做吗?或。
  • 我觉得你应该自己做东西然后打电话给super
  • 我在 update() 中添加了对 super 的调用,以提醒您酌情调用它。实际上,您可能也应该在 create() 中调用 super。我会将它添加到我的示例中。
  • 但是为什么我不能只说 def create super #my code end 然后就没有了?
  • 可以,不需要在update()中调用super()。我的例子可能不是最好的。道歉:-)
【解决方案2】:

实际上没有必要让控制器参与其中;模型可以(并且应该)在这里完成所有繁重的工作。

我假设您在 UserProfile 模型之间存在关系,在这种情况下,您应该能够执行以下操作:

class User < ActiveRecord::Base
  has_one :profile # could be a belongs_to, but has_one makes more sense

  after_create :create_user_profile

  def create_user_profile
    create_profile(:column => 'value', ...)
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多