asf asf - 3 months ago 15
Ruby Question

Ruby on Rails: required parameters for model

Rails 5. I have model User and I want field "login" to be obligatory.

What I did:

class User < ApplicationRecord
has_one :cart

def create
User.create(user_params)
end

private
def user_params
params.require(:user).permit(:login)
end
end


But it doesn't work. I can save new user without login.

irb(main):001:0> user2 = User.create

begin transaction

SQL (1.5ms) INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?) [["created_at", 2016-08-21 11:38:17 UTC], ["updated_at", 2016-08-21 11:38:17 UTC]]

commit transaction

=> #<User id: 4, login: nil, created_at: "2016-08-21 11:38:17", updated_at: "2016-08-21 11:38:17">


How to fix it?

Answer

You need to add validation to User model:

validates :login, presence: true

This piece of code:

def user_params
  params.require(:user).permit(:login)
end

only allows login field to be set from your html form.

Comments