【问题标题】:Ruby on Rails - Devise ConfirmableRuby on Rails - 设计可确认
【发布时间】:2012-08-14 15:36:24
【问题描述】:

我是一名 RoR 新手,正在使用 rails 3.2.3。

我一直在使用 devise,到目前为止效果很好,但是我遇到了问题。

我有一个带有设计的User 表和一个与角色表的HABTM 关联。我创建了连接表,一切都很好。当我创建一个用户并选择它的角色时,它会正确地在连接表中创建数据。

但是,我激活了设计的confirmable 选项,事情开始出错。 当我创建一个新用户时,它不再按应有的方式在联接表中插入记录。

我的意思是,我所做的只是在其他设计选项(例如 :database_authenticatable, :recoverable, :rememberable, :trackable:validatable)前面添加 , :confirmable

当我激活:confirmable 时,我写了这个迁移(我也看到堆栈溢出):

class AddConfirmableToDeviseV < ActiveRecord::Migration
def change
    change_table(:users) do |t| 
      t.confirmable 
    end
    add_index  :users, :confirmation_token, :unique => true 
  end
end

它会发送带有确认链接的电子邮件,这没什么问题,但是当我单击它时,应用程序会中断,因为该用户没有分配给它的角色,这是必须的。

正如我所说,我所做的只是添加:confirmable如果我在我的用户模型中像这样#,:confirmable 将其注释掉,角色和用户数据会正确插入到联接表中。

发生了什么事?有什么建议吗?

提前致谢,

问候

更新

@Kyle C

我正在使用常规操作创建用户:

查看:

<div class="field">
    <%= f.label :username %><br />
    <%= f.text_field :username %>
</div>
(...)

<% for role in Role.find(:all) %>
  <div class="field">
  <%= check_box_tag "user[role_ids][]", role.id, @user.roles.include?(role) %>
  <%= role.name %>
  </div>
<%end%>

然后在我的控制器中:

def create

@user = User.new(params[:user])    

respond_to do |format|
  if @user.save
    format.html { redirect_to(@user, :notice => 'User was successfully created.') }
  (...)

没有:confirmable,这足以在连接表中输入数据。

最重要的是,我的应用控制器中有这个:

def after_sign_in_path_for(resource)

if current_user.roles.first.id == 1
  admin_dashboard_path
elsif current_user.roles.first.id == 2
  manage_path
end

end

如果我把这个去掉,用户在点击确认邮件时会登录,但是,中间的连接表仍然没有得到关联。

我浏览了文档 (https://github.com/plataformatec/devise/blob/master/lib/devise/models/confirmable.rb) 但我还是个菜鸟,我也没有找到任何可以覆盖我的应用程序初始行为的东西。

有没有办法在我创建用户后强制输入连接表中的记录?

我试过了:

def create

@user = User.new(params[:user])
@role = Role.find(params[:user][:role_ids])

if @user.save
@user.role << @role
@user.save

AND(做错事但仍然没有成功)

(...)
if @user.save
query = ActiveRecord::Base.connection.raw_connection.prepare("INSERT INTO roles_users (role_id, user_id) VALUES (?,?);")
query.execute(@role.id, @user.id)
query.close

这真是令人沮丧,其他人在使用 HABTM 激活 :confirmable 时遇到了这个问题?

感谢大家的帮助

【问题讨论】:

  • 检查这个answer 完全相同的问题。检查设计 2.0 文档。
  • 我已经这样做了(:unconfirmed_email 除外),但我的联接表中的角色 (users_role) 仍未创建。会是什么?

标签: ruby-on-rails devise has-and-belongs-to-many devise-confirmable


【解决方案1】:

t.confirmable 不再受支持,请使用此迁移

   ## Confirmable
  # t.string   :confirmation_token
  # t.datetime :confirmed_at
  # t.datetime :confirmation_sent_at
  # t.string   :unconfirmed_email

【讨论】:

  • 我已经完成了这个(除了:unconfirmed_email),但是我的连接表中的角色(users_role)仍然没有被创建。会是什么?
  • 如何将角色添加到用户?它在 after_create 回调中吗?请张贴代码
  • 试试 '@user.roles
  • 感谢 Kyle C,它确实有效,它确实是一个 HABMT,但由于它只是一个用户的一个角色,所以我使用了@user.role &lt;&lt; @role,而这正是问题所在。您的解决方案有效,非常感谢您的问候。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2011-11-18
  • 2011-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多