samedi 17 septembre 2016

Rails 5.0.0.1: can not create a class instance from the console?

I am following a video tutorial made in June 2012. The Ruby version 1.9.3, and Rails version is 3 at that time. Now I am trying out the code examples in Rails 5.0.0.1.

We know that nowadays strong parameters must be used in a create action. Is that also applicable when using the console to create an instance object of a class?

In the exercise a model User was generated by rails g scaffold user name movie. The next instruction was to rake db:migrate(of course), and then go into the console and create a User record. All went well; record created and saved with all fields having a value.

But now comes the part where my question is about: the next command was:

rails g scaffold car user:belongs_to condition year:integer.

OK; rake db:migrate again, and open the console. This happened when I wanted to create a Car record:

>> car = Car.create(year: 2003, condition: 'ok')
   (0.2ms)  begin transaction
   (0.1ms)  rollback transaction
=> #<Car id: nil, user_id: nil, condition: "ok", year: 2003, created_at: nil, updated_at: nil>

No record was created! I suspect it has to do with the strong parameters in Rails 4 and 5?

At last, here are my questions:

  • What went wrong? And is there an alternative way, using the console to create?
  • I know there are gems that 'mimic' a state before strong parameters, but I'd rather not use these; it feels like cheating!

Aucun commentaire:

Enregistrer un commentaire