【问题标题】:Ruby on Rails Database NilingRuby on Rails 数据库 Niling
【发布时间】:2013-12-30 23:51:59
【问题描述】:

所以,我有我的数据库,但每当我调用 Model.create(:thing => "Hi") 时,它都会“执行”。我一看,我的记录都是nils! (减去 ID 和时间戳,它们由活动记录管理。)是我创建它们的方式还是我的模型?我使用的是 Rails 4.0.1,它是对应的活动记录版本。那么,它是什么?什么问题会造成这种情况?

我的日志:irb(main):003:0>

Email.create(:user => User.find(3), :email => "HIDDEN@HIDDEN.HIDDEN", :key => Email.gen("gemist", "HIDDEN@HIDDEN.HIDDEN"))
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1  [["id", 3]]
WARNING: Can't mass-assign protected attributes for Email: user, email, key

   (0.1ms)  begin transaction
  SQL (2.9ms)  INSERT INTO "emails" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", Wed, 01 Jan 2014 21:22:24 UTC +00:00], ["updated_at", Wed, 01 Jan 2014 21:22:24 UTC +00:00]]
   (1.0ms)  commit transaction
=> #<Email id: 3, email: nil, User_id: nil, key: nil, confirmed: nil, created_at: "2014-01-01 21:22:24", updated_at: "2014-01-01 21:22:24">

还有我的模型,如果你想知道 ZE Generate 功能......或者其他什么

class Email < ActiveRecord::Base
  belongs_to :User
  def self.gen(user,email)
    # Make conf keys on demand
    # Salting is used for randominzg and uniquisng, in the case we have already
    # sent keys to the same email (We don't want the samekeys more than once!)
    # Comboing to make sure that incase of two users who want to confirm the 
    # same email
    salt = BCrypt::Engine.generate_salt
    combo = user + email 
    return BCrypt::Engine.hash_secret(combo, salt)
  end
end

如果需要,我可以提供迁移或 schmea。

现在我知道在“如何编辑”下我需要尊重原作者,但我没有自尊。

【问题讨论】:

  • 尝试Model.create!(:thing =&gt; "Hi"),如果没有成功创建实例会抛出异常。发布返回的内容。
  • 这可能不会有太大帮助。根据 The Gemist 所说的 ID 和时间戳 not nil,这些记录显然是持久存在的。您能否向我们展示您的模型代码和您创建模型代码的示例?
  • 你也可以显示你的控制器代码,以及当你创建东西时网络服务器的输出吗?在黑暗中射击:您是否将所有参数都列入了像 params.require(:thing).permit(:attribute1, :attribute2) 这样的强参数块中?

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


【解决方案1】:

您的问题已经包含答案:

WARNING: Can't mass-assign protected attributes for Email: user, email, key

和:

INSERT INTO "emails" ("created_at", "updated_at") VALUES (?, ?)  [["created_at", Wed, 01 Jan 2014 21:22:24 UTC +00:00], ["updated_at", Wed, 01 Jan 2014 21:22:24 UTC +00:00]]

您不能在批量分配期间设置useremailkeycreate() 正在这样做),所以它忽略了这些。从INSERT 日志中可以看到,唯一设置的字段是时间戳字段。所以你最终会在数据库中得到一个相当空的记录。

您可以在模型实例上单独设置这些字段,也可以通过将其放入模型中将它们标记为可批量分配:

attr_accessible :user, :email, :key

不过,您可能非常希望保护它们。这是article on mass-assignment protection。如果您正在处理表单数据,您可能希望保留对某些字段的保护。如果您的 create() 已经在使用受信任的数据,您可以让它们访问。

【讨论】:

  • 是的,就是这样。我使用的是控制台,所以我更喜欢那里的一个班轮。很好!
  • OP说他正在使用Rails 4。如果他想使用attr_accessible需要使用受保护的属性gem - github.com/rails/protected_attributes
猜你喜欢
  • 1970-01-01
  • 2011-10-02
  • 2016-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-15
相关资源
最近更新 更多