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

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

    I found a solution that works fairly well, and is ultimately a combination of the above options. It allows for invalid params to be passed (and ignored), while valid ones are mapped correctly to the object.

    def self.initialize(params={})
      User.new(params.reject { |k| !User.attribute_method?(k) })
    end
    

    Now rather than calling User.new(), call User.initialize(). This will "filter" the correct params fairly elegantly.

提交回复
热议问题