Rails: Show error messages in fields_for with store_accesor (json)

80 Views Asked by At

I have a jsonb column named details in my User model, I am using store_accesor to add data to group and I am trying to do some validations.

# models/user.rb
validate :validation_params
store_accessor :details, :group

def validation_params
  if !groups.nil?
    errors.add :phone, :blank if phone.blank?
    errors.add :group_name, :blank if group["name"].blank?
  end
end
# controllers/update_controller.rb
def new
  @user = User.new(details: {group: {name: nil}})
end

def signup
  @user = User.new user_params
  if @user.valid?
    @user.save
    redirect_to :root, success: "Yay"
  else
    render :new
  end
end

private

def user_params
  params.require(:user).permit(:phone, group: [:name])
end

The next form is working great and is saving everything as it should when there's no user errors. It is even making the validation and rendering the new page but is not showing the error in the specific group name field.

# views/new.html.erb
<%= simple_form_for @user: :signup do |form| %>
  <%= form.input :phone %>
  <%= form.simple_fields_for :group, @user.group do |field| %>
    <%= field.input :name %>
  <% end %>
  <%= form.submit "Update" %>
<% end %>

So my main question here is how can I do that?. I've tried with :"group.name", :group_name and some other similar stuff in the errors add method without success, the other association and attributes fields like :phone work just fine.

These are the returning errors:

#<ActiveModel::Error attribute=phone, type=blank, options={}>,
#<ActiveModel::Error attribute=group_name, type=blank, options={}>,

And just for fun, it would be great if there's a way to use translations as labels in fields_for. In the next yml file I have also tried with group.name, group_name and nothing:

# config/locales/es.yml
es:
  activerecord:
    attributes:
      user:
        phone: Teléfono móvil
        group:
          name: Grupo

Here is the unwanted result of everything:

enter image description here

Another thing, the info inside the fields_for input is being erased when I send the form, but using byebug before the render, @user.group is showing {name: "Some group"}, cause as I said, the user and its group name is saving without issues when is valid.

I have a more complex form rather than just grabbing the phone and the group name but I am trying to be short here and I know there's a way to achieve everything, what am I missing?

0

There are 0 best solutions below