0
class UsersController < ApplicationController
....
  def update
    if @user.update(edit_user_params)
      flash[:success] = 'Profilo aggiornato correttamente'
      redirect_to user_path(@user)
    else
      render action: 'edit'
    end
  end
....

  private
  def edit_user_params
    params.require(:user).permit(:email, information_attributes: [:name, :surname, :date_of_birth, :address, :city, :country, :post_code, :phone])
  end
end

As all you can see I have nested forms.

The Informatation model is made by the following column:

  • name
  • surname
  • date_of_birth
  • address
  • city
  • country
  • post_code
  • phone
  • credit

In the nested forms there is not an input field for the credit, because to update the credit I created another flow.

The problem is the following, when rails does @user.update(edit_user_params) it goes to overwrite all the columns of the Information row related to the particular user, that is, if the credit was 15$ after the update it becomes 0. What does that happen? Shouldn't the update method update only the columns pointed in ()?

In addiction, because in the Information.rb I have the following validate:

validates :credit, numericality: { greater_than_or_equal_to: 0.01 }

I always get an error because the credit field results equals to 0.0

2 Answers 2

2

I've had this problem before. Here's the fix:

params.require(:user).permit(:email, information_attributes: [:id, :name, :surname, :date_of_birth, :address, :city, :country, :post_code, :phone])

You need to add :id to information_attributes. I am not sure how secure it is (If you find out, please let me know), but it will fix the problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, I worked it out adding in the model User the following: accepts_nested_attributes_for :information, update_only: true, that is I added the option update_only: true
0

I somehow suspect that your edit_user_params function is getting in the way of this working. Why not use validations in your user model, i.e. validates :user, :presence => true and then just pass params directly into the update statement? Also, it might be helpful to see the code of your actual form. What fields are in the form?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.