Search code examples
ruby-on-railsrubyruby-on-rails-4scaffolding

Ruby on rails scaffold model validation questions


I am trying to follow a ruby on rails scaffold example.

I am using ruby version: 2.1.5 with rails version : 4.1.8

I have used this command:

rails generate scaffold User name:string email:string

This worked fine - I can run the example which shows crud functionality to my generated scaffold. The examples I have been following advise to look at the model file generated. The ones in the examples seemed to have a value called attr_accessible - but for me this was not generated - I do not know why - it seems to be quite useful so you can easily see what is inside your model? My model looks like this:

class User < ActiveRecord::Base

end

I altered it to look like this :

class User < ActiveRecord::Base
    attr_accessible :name, :email
    validates :name, :presence=>true
end

and when I now visit localhost/users I get the error:

Error

Can somebody please tell me how a generated model can be created with this attr_accessible line, and how I can add an example of validation to the model.


Solution

  • Rails 4 doesn't use attr_accessible; it uses Strong Parameters.

    They both serve as a guard for mass assignment of params, often times used during form submissions.

    The scaffold doesn't support automatically setting strong params as far as I'm aware, in part because people implement strong params white listing very differently.

    A couple more links on Strong Params

    To me this suggests whatever guide you're following is out of date.