rails Model.create(:attr=>"value") returns model with uninitialized fields -


this stumping me. process works fine if go #new , #save, #create returns model instance fields set nil.

e.g: unexpected behavior:

ruby-1.9.2-p0 > emaildefault.create(:description=>"hi")  => #<emaildefault id: nil, description: nil, created_at: nil, updated_at: nil>  

expected behaviour:

ruby-1.9.2-p0 > e = emaildefault.new  => #<emaildefault id: nil, description: nil, created_at: nil, updated_at: nil>  ruby-1.9.2-p0 > e.description = "hi"  => "hi" ruby-1.9.2-p0 > e.save  => true  ruby-1.9.2-p0 > emaildefault.last  => #<emaildefault id: 4, description: "hi", created_at: "2011-02-27 22:25:33", updated_at: "2011-02-27 22:25:33">  

what doing wrong?

--update-- turns out mis-using attr_accessor. wanted add non-database attributes, did with:

attr_accessible :example_to, :cc_comments

which wrong, , caused situation @heikki mentioned. need is:

attr_accessor :example_to, :cc_comments

you need white list properties attr_accessible enable mass-assignment.

http://api.rubyonrails.org/classes/activemodel/massassignmentsecurity/classmethods.html#method-i-attr_accessible

--edit

by default attributes available mass-assignment. if attr_accessible used mass-assignment work attributes. attr_protected works opposite way ie. attributes protected mass-assignment. 1 should used @ time. prefer white listing attr_accessible.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -