attr_accessor vs attr_accessible

Please guide me how to use those two methods. I can't differentiate them. I was doing something on my model and I have put one field in the attr_accessible method. After that when I try to run the app the app always says my other fields are blank, but they're all filled up. What's wrong with it?

Thanks

Hi James,

attr_accessible is used to identify attributes that are accessible by your controller methods. This is to protect your models from being written to by malicious users posting values that they shouldn't be into your create and update methods. All of your fields are blank except the one that you specified to be accessible because rails is doing it's job :slight_smile:

attr_accessible will only allow access to the attributes that you specify, denying the rest. attr_protected will deny access to the attributes that you specify, allowing the rest, and specifying neither in your model will allow access to all attributes.

attr_accessor is an easy way to create read and write accessors in your class. attr_accessor :myvar replaces the following.

def myvar   @myvar end

def myvar=(myvar)   @myvar=myvar end

hope that helps.

Jason

Hi Jason,

That was really a well explained. But I find some things that works not according to what you've said.

I have a model with 6 attributes. And in my controller I only access the password attribute. So I code attr_accessible :password. All of the sudden the validates method doesn't work as it should be. Even if the fields where filled up correctly the validates method keeps on triggering, until I put all my attributes to attr_accessible. But everything was working well when I haven't code attr_accessible :password.