title: Validate uniqueness of a value with scope - Ruby on Rails 5
body: <p>I have table <code>posts</code> with a model <code>Post</code> and table languages (columns - id, post_id, language) with a model <code>Language</code>. Post has many languages and Language belongs to a Post. In the post model I have:</p>
  
  <p>Post model:</p>
  
  <pre><code>has_many :languages
  validates_associated :languages
  </code></pre>
  
  <p>Language model:</p>
  
  <pre><code>belongs_to :post
  validates_uniqueness_of :language, scope: :post_id
  </code></pre>
  
  <p>language is the column in the table languages. </p>
  
  <p>The language field is allowed in the posts_controller (strong parameters):</p>
  
  <pre><code>def post_params
      params.require(:post).permit(:languages_attributes =&gt; [:language], ...)
  </code></pre>
  
  <p>This is the view for the form for creating a post:</p>
  
  <pre><code>&lt;%= form_for @post do |f| %&gt;
      .....
      &lt;%= f.fields_for :languages do |language| %&gt;
          &lt;%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %&gt;
          &lt;%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %&gt;
          &lt;%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %&gt;
          &lt;%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %&gt;
      &lt;% end %&gt;
  </code></pre>
  
  <p>This is create post method:</p>
  
  <pre><code>@post= Post.new(post_params)
  if @post.save
  ....
  </code></pre>
  
  <p>I want to validate uniqueness of the languages with scope of the post (scope: :post_id) and every post to have only 1 time English language for the example. The post can have more than 1 languages, but different languages. </p>
  
  <p>I tried with <code>validates_uniqueness_of :language, scope: :post_id</code>, but if I add two times English (all lowercase), there is no error for this and the data is inserted to the tables. </p>
  
  <p>How to validate uniqueness of the languages for a post with the scope of the current post ?</p>
  
  <p>EDIT: I see that this is a bug in Rails - <a href="https://github.com/rails/rails/issues/20676" rel="noreferrer">GitHub</a>, but I still need a solution.</p>