Rails: Ignoring non-existant attributes passed to create()

前端 未结 8 1158
执笔经年
执笔经年 2021-02-03 22:12

I have the following Rails model:

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


        
8条回答
  •  执笔经年
    2021-02-03 22:36

    I came up with a solution that looks like this, you might find it helpful:

    def self.create_from_hash(hash)
      hash.select! {|k, v| self.column_names.include? k }
      self.create(hash)
    end
    

    This was an ideal solution for me, because in my case hash was coming from an ideal data source which mirrored my schema (except there were additional fields).

提交回复
热议问题