<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Robin Seo on Medium]]></title>
        <description><![CDATA[Stories by Robin Seo on Medium]]></description>
        <link>https://medium.com/@robinseo?source=rss-7c9c800de2bb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LEt1IUBXcTBAC4wK1MRfxg.jpeg</url>
            <title>Stories by Robin Seo on Medium</title>
            <link>https://medium.com/@robinseo?source=rss-7c9c800de2bb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 16:38:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@robinseo/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Mastering Rails Validation - 6 Tips and Techniques]]></title>
            <link>https://blog.devops.dev/mastering-rails-validation-6-tips-and-techniques-d7c84ee051d9?source=rss-7c9c800de2bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7c84ee051d9</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[validation]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Robin Seo]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 13:02:14 GMT</pubDate>
            <atom:updated>2023-03-17T16:18:35.900Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fWpMA8mvKTMRDnUpq18Cgg.png" /><figcaption>Photo by <a href="https://unsplash.com/ko/@jasondeblooisphotography">Jason D</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Rails provides a wide range of validation options to ensure data integrity and consistency. In this article, we will dive into the world of Rails validation and explore some of its most useful features. This guide will provide you with practical tips and techniques to ensure your application’s data is always valid and error-free.</p><h3>Validate Boolean</h3><p>Before explain validate boolean, Let me explain How ActiveRecord casts value to boolean. Here’s how it works.</p><pre># Followings return true<br>ActiveRecord::Type::Boolean.new.cast(&quot;true&quot;)<br>ActiveRecord::Type::Boolean.new.cast(&quot;TRUE&quot;) <br>ActiveRecord::Type::Boolean.new.cast(&quot;literally, any string&quot;)<br>ActiveRecord::Type::Boolean.new.cast(1)<br>ActiveRecord::Type::Boolean.new.cast(&quot;1&quot;)<br><br># Followings return false<br>ActiveRecord::Type::Boolean.new.cast(&quot;False&quot;)<br>ActiveRecord::Type::Boolean.new.cast(&quot;false&quot;) <br>ActiveRecord::Type::Boolean.new.cast(0)<br>ActiveRecord::Type::Boolean.new.cast(&quot;0&quot;)<br><br># Following returns nil<br>ActiveRecord::Type::Boolean.new.cast(&quot;&quot;)</pre><p>Here’s the way to validate boolean easily.</p><pre>class InterpretationBooking &lt; ApplicationRecord<br>  validates :include_lunchtime, inclusion: { in: [true, false], message: &quot;doesn&#39;t allow null value&quot; }, allow_nil: false<br>end</pre><pre># the followings have &quot;include_lunchtime&quot; as true<br>InterpretationBooking.create!(include_lunchtime: true)<br>InterpretationBooking.create!(include_lunchtime: 1)<br>InterpretationBooking.create!(include_lunchtime: &quot;true&quot;) <br><br><br># the followings have &quot;include_lunchtime&quot; as false<br>InterpretationBooking.create!(include_lunchtime: false)<br>InterpretationBooking.create!(include_lunchtime: 0)<br>InterpretationBooking.create!(include_lunchtime: &quot;false&quot;)<br><br><br># the followings raise error<br>InterpretationBooking.create!(include_lunchtime: nil)<br>InterpretationBooking.create!(include_lunchtime: &quot;&quot;)<br># =&gt; ActiveRecord::RecordInvalid (Validation failed: Include lunchtime doesn&#39;t allow null value)</pre><p>Note : Even if you set the NOT NULL constraint to column, this validator would be act first.</p><h3>Validate Date and Time</h3><p><a href="https://github.com/adzap/validates_timeliness">validates_timeliness</a> gem provides seamless and convenient validator.</p><pre>class Booking &lt; ApplicationRecord<br>  validates_date :arrival_date, allow_blank: true<br>  validates_time :arrival_time, allow_blank: true<br>end</pre><p>This gem supports regular validation options such as allow_nil, allow_blank, if, on. Furthermore, It provides time and date specific restriction options such as is_at, before, on_or_after, between.</p><h3>Scoped Validation</h3><p>You can specify a column or scope as a scope and validation within it.</p><pre>class PatientNumber &lt; ApplicationRecord<br> belongs_to :user<br>  belongs_to :hospital<br> ...<br> validates :hospital_id, uniqueness: { message: &quot;User already have PatientNumber on Hospital(id=%{value})&quot;, scope: :user_id }<br> validates :primary, uniqueness: { message: &quot;PatientNumber Already Taken&quot;, scope: :user_id }, if: :primary<br><br> scope :primary, -&gt; { where(primary: true).last }<br> ...<br>end</pre><p>You can even specify where condition instead scope.</p><pre>class InterpretationBooking &lt; ApplicationRecord<br> ...<br> validates :outpatient_booking_id, uniqueness: { message: &quot;already has active interpretation booking&quot;, conditions: -&gt; { where(canceled_at: nil) }<br> ...<br>end</pre><h3>Your Own Validation Message</h3><p>You can create sophisticated validation message based on record with lambda.</p><pre>class TeamMember &lt; ApplicationRecord<br> validates_uniqueness_of :user_id,<br>                          message: -&gt; (record, _) { &quot;(user_id=#{record.user_id}) try to appending already in Team (team_id=#{record.team_id})&quot; },<br>                          scope: :team_id<br><br>end</pre><h3>Validation for optional belongs_to</h3><pre>class InterpretationBooking &lt; ApplicationRecord<br>  belongs_to :outpatient_booking<br>  belongs_to :interpreter, optional: true<br>end</pre><p>In your database, Only four interpreters exists(id=[1,2,3,4]). In this situation, InterpretationBooking can take interpreter on two way.</p><p>First way is taking interpreter_id.</p><pre>ob = OutpatientBooking.first<br>InterpretationBooking.create!(outpatient_booking: ob, interpreter_id: 99999)</pre><p>Second way is taking interpreter record.</p><pre>ob = OutpatientBooking.first<br>ip = Interpreter.find(99999)<br>InterpretationBooking.create!(outpatient_booking: ob, interpreter: ip)</pre><p>In first way, the code doesn’t raise exception even the model got a interpreter_id doesn’t exist in database. On the other hand, second way raise ActiveRecord::RecordNotFound exception. For unified behavior, you can add a validation like below.</p><pre>class InterpretationBooking &lt; ApplicationRecord<br>  belongs_to :outpatient_booking<br>  belongs_to :interpreter, optional: true<br>  validates_presence_of :interpreter, if: :interpreter_id<br>end</pre><p>As personal preference, I prefer second way to create/update the record. Although the model has validator for optional belongs_to, it raises ActiveRecord::RecordInvalid (Interpreter cant&#39; be blank). Personally, ActiveRecord::NotFound exception is more explicit exception in this context. Here’s the example snippet for using second way in controller.</p><pre>class InterpretationBookingController &lt; ApplicationController<br>  def create<br>    @interpretation_booking = InterpretationBooking.create!(create_params)<br>  end<br><br>  private<br>  def create_params<br>    params.permit(:outpatient_booking, :interpreter)<br>          .merge({ outpatient_booking: OutpatientBooking.not_canceled.find(params[:outpatient_booking_id]) })<br>          .then { |merged_params| params.key?(:interpreter_id) ? merged_params.merge({ interpreter_pool: Interpreter.find(params[:interpreter_id]) }) : merged_params }<br>  end<br>end</pre><p>Note: Above controller uses centralized error handling. see <a href="https://medium.com/@robinseo/rails-api-elegant-error-handling-the-centralized-way-c564dc5d1fa3">this article</a>.</p><h3>Handle Enum</h3><p>Enum! It’s powerful but troublesome. One of critical problem is raising ArgumentError when the record receive invalid value. Let me explain with following simple User model.</p><pre>class User &lt; ApplicationRecord<br>  enum gender: %w(male female)<br>end</pre><p>When you try to assign invalid value, it raise ArgumentError.</p><pre>user = User.new<br>user.gender = &quot;awesome&quot;<br># =&gt; ArguementError(&#39;awesome&#39; is not valid gender)</pre><p>When you try to create! (bang method), it raise ArgumentError.</p><pre>user = User.create!(name: &quot;robin&quot;, gender: &quot;awesome&quot;)<br># =&gt; ArguementError(&#39;awesome&#39; is not valid gender)</pre><p>It’s puzzling point. When you try to create, it raise ArgumentError instead return false. This behavior may puzzle you because you expect create method doesn’t raise error but it actually raise.</p><pre>user = User.create(name: &quot;robin&quot;, gender: &quot;awesome&quot;)<br># =&gt; ArguementError(&#39;awesome&#39; is not valid gender)</pre><p>Note that ArgumentError is thrown before the any validation. For this reason, you cannot validate with validator. If the purpose of validation is get unified exception, I can gave following solution. “the monkey-patch”</p><pre># config/initializers/monkey_patches/initializers/active_record_enum.rb<br>module ActiveRecord<br>  module Enum<br>    class EnumType &lt; Type::Value<br>      def assert_valid_value(value)<br>        unless value.blank? || mapping.has_key?(value) || mapping.has_value?(value)<br>          raise YourOwnExceptionHere, &quot;Validation Failed: &#39;#{value}&#39; is not a valid #{name}&quot;<br>        end<br>      end<br>    end<br>  end<br>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7c84ee051d9" width="1" height="1" alt=""><hr><p><a href="https://blog.devops.dev/mastering-rails-validation-6-tips-and-techniques-d7c84ee051d9">Mastering Rails Validation - 6 Tips and Techniques</a> was originally published in <a href="https://blog.devops.dev/">DevOps.dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails API elegant error handling — The centralized way]]></title>
            <link>https://robinseo.medium.com/rails-api-elegant-error-handling-the-centralized-way-c564dc5d1fa3?source=rss-7c9c800de2bb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c564dc5d1fa3</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Robin Seo]]></dc:creator>
            <pubDate>Sat, 19 Mar 2022 13:07:55 GMT</pubDate>
            <atom:updated>2022-03-19T14:41:42.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rails API elegant error handling — The centralized way</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N6roF5TfdUYJbbyb" /><figcaption>Photo by <a href="https://unsplash.com/@agforl24?utm_source=medium&amp;utm_medium=referral">Tai Bui</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Rails application raise error on various context. for example, ActiveRecord find method raise ActiveRecord::RecordNotFound when it couldn’t find record with given condition.</p><p>Rails application has built-in error handler which is in Rack middleware. In case of ActiveRecord::RecordNotFound, Rails API application respond with error described on below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41e126c20cd11f4a88a79a66801c5537/href">https://medium.com/media/41e126c20cd11f4a88a79a66801c5537/href</a></iframe><p>Since the rails always ready to handle the error, You can focus on write your business logic and feel free from rescue error. This article introduces several ways to handle error in centralized way from easy way to elegant way.</p><h3>Easy Way — Just leave the error raised</h3><p>You can simply let your logic raise an error if it a response is enough from Rack middleware. You can write the controller like following.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53a8ef3ee961b7cb76884278a2ad7981/href">https://medium.com/media/53a8ef3ee961b7cb76884278a2ad7981/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o6MbkWQI5OazCn8cM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fseason-16-the-simpsons-16x3-3o6MbkWQI5OazCn8cM&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2F3o6MbkWQI5OazCn8cM%2Fgiphy.gif%3Fcid%3D790b7611432a28b976c4c07fe8f2490c5417f1ac189b145a%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b08839f19836faa25c3c6bee1f5e311/href">https://medium.com/media/8b08839f19836faa25c3c6bee1f5e311/href</a></iframe><h3>Good Way — Let ApplicationController handle specific exceptions</h3><p>ActionController provides rescue_from method which handle errors raised from the controller. Here is the example from Rails API document.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/431ca0473276eaf2e2f2eb01a596344a/href">https://medium.com/media/431ca0473276eaf2e2f2eb01a596344a/href</a></iframe><p>It’s good enough, but the modular approach is better way since ApplicationController may have bunch of stuffs to do.</p><h3>Better Way — Let the module handle it</h3><p>Let’s create the module for ApplicationController to handle errors. First of all, define the spec of error response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e8d618fbbb65d26f5f0f64ef60d3537/href">https://medium.com/media/9e8d618fbbb65d26f5f0f64ef60d3537/href</a></iframe><p>Let’s write the module. This module has Handler and several error classes. Handler has logics for rescuing error written in above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/202cba329c25512b23a26437b5fd2908/href">https://medium.com/media/202cba329c25512b23a26437b5fd2908/href</a></iframe><p>Let the application autoload classes and modules in lib directory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5198506cf45870f8340505f6dfbb3fa9/href">https://medium.com/media/5198506cf45870f8340505f6dfbb3fa9/href</a></iframe><p>Finally, include ApiException::Handler module in ApplicationController. Every error in controllers extend ApplicationController would be handled by ApiException::Handler</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ab83e55ed0253605f188abce4f5a120/href">https://medium.com/media/0ab83e55ed0253605f188abce4f5a120/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl2Je19AZkPF7r6gXm%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fseason-15-the-simpsons-15x4-l2Je19AZkPF7r6gXm&amp;image=https%3A%2F%2Fmedia3.giphy.com%2Fmedia%2Fl2Je19AZkPF7r6gXm%2Fgiphy.gif%3Fcid%3D790b76115af1361d0e850cdc3428927679666ed2b7142c75%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="328" frameborder="0" scrolling="no"><a href="https://medium.com/media/384d921229f03444bf6dcd63707ece49/href">https://medium.com/media/384d921229f03444bf6dcd63707ece49/href</a></iframe><h3>Best Way — Let’s make an advance in ApiException Module</h3><p>Let’s take a closer look at the way above.</p><h4><strong>The Problem — It has a difficulty to handle rails built-in exceptions</strong></h4><p>Rails built-in exceptions (e.g. ActiveRecord::RecordNotFound) would not respond with our spec. Following is a simple way to overcome.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/165ca41ee344fe48fd523b7ee58c7f67/href">https://medium.com/media/165ca41ee344fe48fd523b7ee58c7f67/href</a></iframe><p>With this approach, you always re-raise error on every built-in errors and even difficult to use messages in built-in error. Instead this, let the module handle both your custom error and built-in error.</p><p>Note that you can see the list of built-in errors handled by Rack with command below.</p><pre>$ rails r &quot;pp ActionDispatch::ExceptionWrapper.rescue_responses&quot;</pre><h4><strong>The problem — Bad readability</strong></h4><p>You would write 8-line codes to define error class which has deadly simple information.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/edc5e776bd478299ea844fd1d5fd9292/href">https://medium.com/media/edc5e776bd478299ea844fd1d5fd9292/href</a></iframe><p>To improve readability, let describe error information in hash.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/674b4d12b5d71e0ed46371233b7dc2c7/href">https://medium.com/media/674b4d12b5d71e0ed46371233b7dc2c7/href</a></iframe><p>Thanks to ruby is dynamic language, you can define class on runtime. Let ApiException::Handler find or create the error class by the name before executing rescue_from method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dccac03d4936f54c66992e710b75c74f/href">https://medium.com/media/dccac03d4936f54c66992e710b75c74f/href</a></iframe><h4><strong>Improvement — Additional slot for detail message</strong></h4><p>Built-in error throw additional information sometimes. for example, ActiveRecord validator raise ActiveRecord::RecordInvalid with detailed message.</p><pre>Post.create! <br>&gt;&gt; ActiveRecord::RecordInvalid (Validation failed: Title can&#39;t be blank)</pre><p>You can even raise your own error with additional message.</p><pre>raise StandardError, &quot;My awesome error message&quot; <br>&gt;&gt; StandardError (My awesome error message)</pre><p>Let the handler respond with detailed message in detail field if raised error has an additional message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ba85a0f6e81245dd877582632944524/href">https://medium.com/media/5ba85a0f6e81245dd877582632944524/href</a></iframe><p>The complete code is following. the toy project for this article in <a href="https://github.com/robinseo/rails-centralized-error-handling">here</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e347de96bf63dd9bcc410fce80e6d7e/href">https://medium.com/media/9e347de96bf63dd9bcc410fce80e6d7e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c564dc5d1fa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>