Rails:忽略传递给 create() 的不存在的属性 [英] Rails: Ignoring non-existant attributes passed to create()

查看:44
本文介绍了Rails:忽略传递给 create() 的不存在的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下 Rails 模型:

I have the following Rails model:

class CreateFoo < ActiveRecord::Migration
  def self.up
    create_table :foo do |t|
      t.string :a
      t.string :b
      t.string :c
      t.timestamps
    end
  end

  def self.down
    drop_table :foo
  end
end

如果我尝试使用附加的不存在的属性创建新记录,则会产生错误:

If I try and create a new record with an additional non-existent attribute, this produces an error:

Foo.create(a: 'some', b: 'string', c: 'foo', d: 'bar')
ActiveRecord::UnknownAttributeError: unknown attribute: d

有没有办法让 create() 忽略模型中不存在的属性?或者,在创建新记录之前删除不存在的属性的最佳方法是什么?

Is there a way I can get create() to ignore attributes that don't exist in the model? Alternatively, what is the best way to remove non-existent attributes prior to creating the new record?

非常感谢

推荐答案

试图想一个可能更有效的方法,但现在:

Trying to think of a potentially more efficient way, but for now:

hash = { :a => 'some', :b => 'string', :c => 'foo', :d => 'bar' }
@something = Something.new
@something.attributes = hash.reject{|k,v| !@something.attributes.keys.member?(k.to_s) }
@something.save

这篇关于Rails:忽略传递给 create() 的不存在的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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