Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Set att_accessors from parameters hash #7

Open
JoshMcKin opened this issue Oct 4, 2010 · 4 comments
Open

Set att_accessors from parameters hash #7

JoshMcKin opened this issue Oct 4, 2010 · 4 comments

Comments

@JoshMcKin
Copy link

Using simple_record, if you have a model with attr_accessor(s), the attr_accessors are not set if their value is present in the params hash for new objects.

class Foo < SimpleRecord::Base
has_attributes :stuff

attr_accessor :bar

end

f = Foo.new(:bar => "test, :stuff => "yep")
f.stuff # puts "yep"
f.bar # puts nil instead of "test"

I came up with this: http://gist.github.com/609851

@appoxy
Copy link
Collaborator

appoxy commented Oct 17, 2010

Does it work like you suggest in ActiveRecord?

@JoshMcKin
Copy link
Author

I believe so. I find it usefull usually for setting getting unencrypted_passwords, and confirmation password.
class User < ActiveRecord::Base

attr_accessor :password, :password_confirmation

end

u = User.new({:password => "test", :confirmation_password => "test"})

puts u.password
"test"

puts u.confirmation_password
"test"


class SimpleUser < SimpleRecord::Base

attr_accessor :password, :password_confirmation

end

u = SimpleUser.new({:password => "test", :confirmation_password => "test"})
puts u.password
nil

puts u.confirmation_password
nil

If you have access see Ch 11 of Agile Web Development with Rails 2 for a more detailed example

@appoxy
Copy link
Collaborator

appoxy commented Oct 21, 2010

Ok, I'll look at it soon. In the meantime, you could just set it with u.confirmation_password = "test"

@JoshMcKin
Copy link
Author

Actually did this in my model:

def self.new_params(params)

user = User.new

params.each do |param|

# make sure method exists before sending

if user.respond_to?(param[0].to_s)

  user.send(param[0].to_s + "=",param[1])

 end

end

user # return user

end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant