CodexBloom - Programming Q&A Platform

How to handle multilingual content with ActiveRecord validations in Rails 7?

๐Ÿ‘€ Views: 159 ๐Ÿ’ฌ Answers: 1 ๐Ÿ“… Created: 2025-06-02
ruby-on-rails activerecord i18n Ruby

I'm refactoring my project and Hey everyone, I'm running into an issue that's driving me crazy. I'm working on a Rails 7 application that needs to support multilingual content for a `Post` model. Each post can have multiple translations, and I'm using a `translations` table with a `belongs_to :post` relationship. The question arises when I try to validate the presence of translated fields. Here's my setup: ```ruby class Post < ApplicationRecord has_many :translations, dependent: :destroy accepts_nested_attributes_for :translations end class Translation < ApplicationRecord belongs_to :post validates :title, presence: true validates :content, presence: true end ``` When I create a new post with translations, I expect it to validate that at least one translation has a title and content. However, when I submit the form without any translations, I'm getting the following behavior: ``` Translation title canโ€™t be blank Translation content canโ€™t be blank ``` This behavior message shows up even when I correctly set the `accepts_nested_attributes_for` option. Iโ€™ve tried using a custom validation method in the `Post` model to check if at least one translation is present, but I canโ€™t seem to get it to work effectively. Here's what I attempted: ```ruby class Post < ApplicationRecord has_many :translations, dependent: :destroy accepts_nested_attributes_for :translations validate :at_least_one_translation private def at_least_one_translation if translations.blank? || translations.all? { |t| t.title.blank? || t.content.blank? } errors.add(:translations, 'must have at least one valid translation') end end end ``` However, I still encounter validation errors related to the individual translation fields rather than the custom check for the presence of a valid translation. Iโ€™m unsure how to configure the validations so that it only triggers the custom behavior when there are no valid translations. Any advice on how to properly handle this scenario would be greatly appreciated! This is part of a larger application I'm building. Thanks in advance! I've been using Ruby for about a year now. Could this be a known issue?