denniss
denniss

Reputation: 17599

Ignoring extra keys in a hash passed in to create

Does rails provide a way to ignore extra keys that are passed in to create. Supposed User has two attributes, first_name and last_name. When I do

User.create({ :first_name => "first", :last_name => "last", :age => 10})

that line gives me an UknonwnAttributeError. Well, that makes sense, it happens cause age is not one of the attributes.

But is there a way to just ignore key-value pair that is not one of the attributes for User?

Upvotes: 0

Views: 296

Answers (2)

sameera207
sameera207

Reputation: 16629

I guess, you could do this by declaring a virtual attribute as 'age'

Example:

class User < ActiveRecord::Base
  attr_accessor :age
end

Upvotes: 0

Tiago
Tiago

Reputation: 1337

Either what sameera207 said or

hash.keep_if { |k,v| User.attribute_names.include?(k.to_s) }

Ultimately you could override your User model's create method to reject unexacting attributes but i think that's not appropriate.

Upvotes: 1

Related Questions