Search code examples
ruby-on-railsrubyruby-on-rails-3hstore

How to reject update attribute if param is blank or empty?


I have form

View

<%= simple_form_for User.new do |f| %>
   <%= f.input :email %>
   <%= text_field_tag "user[data[first_name]]" %>
   <%= f.button :submit %>
<% end %>

Controller#create

@user = User.find_or_initialize_by_email(params[:user][:email])

if @user.update_attributes(params[:user])
  ...

How to reject update user hstore date attribute if params(in that case first_name) is empty or blank?


Solution

  • In my opinion you are taking a wrong strategy for the create action. Just do

    @user = User.new(params[:user])
    @user.save
    

    If you want to ensure that email is unique across users, use a Rails' validation like so:

    class User
      #...
      validates_uniqueness_of :email
      #...
    end
    

    Your approach will modify an existing user with the same email during a create. Sounds wrong.

    For more details, have a look at the create of a scaffolded controller.