Hugo
Hugo

Reputation: 2444

Rails update object without supplying fields with validates presence: true

I'm trying to update a user object through a form. However, I don't want to allow usernames to be changed. I don't have the field present on the form. When I submit the form, it gives me an error that I cannot leave the username confirmation blank. Here's my controller:

def update
    @partner = CommunityPartner.find(params[:id])
    if @partner.update_attributes(allowed_update_params)

    else
        render('edit')
    end
end

def allowed_create_params
        params.require(:community_partner).permit(:name, :username, :display_email,
                                                                                            :username_confirmation,
                                                                                            :contact_method, :password, 
                                                                                            :password_confirmation,
                                                                                            :phone_number, :address,
                                                                                            :description, :tags_string)
    end

def allowed_update_params
        params.permit!(:name) if params[:name]
        params.permit!(:display_email) if params[:display_email]
        params.permit!(:contact_method) if params[:contact_method]
        params.permit!(:phone_number) if params[:phone_number]
        params.permit!(:address) if params[:address]
        params.permit!(:description) if params[:description]
        params.permit!(:tags_string) if params[:tags_string]
    end

How can I update only the params I'm allowing in the update action without touching the others?

EDIT: validation methods

validates(:name, presence: { on: :create })
validates(:username, presence: { on: :create }, confirmation: { on: :create }, uniqueness: true)
validates(:contact_method, presence: { on: :create })
validates(:username_confirmation, presence: { on: :create })
validates(:display_email, format: { with: VALID_EMAIL })
validates(:address, presence: { on: :create })
validates(:phone_number, presence: { on: :create })
validates(:description, presence: { on: :create })

Upvotes: 0

Views: 212

Answers (2)

neo-code
neo-code

Reputation: 1076

You can skip validation using update_all helper instead of update_attributes.

Upvotes: 0

Kirti Thorat
Kirti Thorat

Reputation: 53028

Assuming that you have a validation on username_confirmation in the CommunityPartner model.

Use on: :create option on that validation. So, that validation would only be checked at the time of CommunityPartner record creation and not while updating(where you don't pass username_confirmation).

For example:

class CommunityPartner < ActiveRecord::Base
  validates :username_confirmation, presence: true, on: :create
end

Upvotes: 2

Related Questions