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

前端 未结 8 1155
执笔经年
执笔经年 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:43

    Re: Is there a way I can get create() to ignore attributes that don't exist in the model? -- No, and this is by design.

    You can create an attr_setter that will be used by create --

    attr_setter :a # will silently absorb additional parameter 'a' from the form.
    

    Re: Alternatively, what is the best way to remove non-existent attributes prior to creating the new record?

    You can remove them explicitly:

    params[:Foo].delete(:a) # delete the extra param :a
    

    But the best is to not put them there in the first place. Modify your form to omit them.

    Added:

    Given the updated info (incoming data), I think I'd create a new hash:

    incoming_data_array.each{|rec|
      Foo.create {:a => rec['a'], :b => rec['b'], :c => rec['c']} # create new
                                                                  # rec from specific
                                                                  # fields
    }
    

    Added more

    # Another way:
    keepers = ['a', 'b', 'c'] # fields used by the Foo class.
    
    incoming_data_array.each{|rec|
      Foo.create rec.delete_if{|key, value| !keepers.include?(key)} # create new rec
    }                                                               # from kept
                                                                    # fields
    
    0 讨论(0)
  • 2021-02-03 22:46

    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
    
    0 讨论(0)
提交回复
热议问题