Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate uniqueness of a value with scope - Ruby on Rails 5

I have table posts with a model Post and table languages (columns - id, post_id, language) with a model Language. Post has many languages and Language belongs to a Post. In the post model I have:

Post model:

has_many :languages
validates_associated :languages

Language model:

belongs_to :post
validates_uniqueness_of :language, scope: :post_id

language is the column in the table languages.

The language field is allowed in the posts_controller (strong parameters):

def post_params
    params.require(:post).permit(:languages_attributes => [:language], ...)

This is the view for the form for creating a post:

<%= form_for @post do |f| %>
    .....
    <%= f.fields_for :languages do |language| %>
        <%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %>
        <%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %>
        <%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %>
        <%=language.select :language, ['english', 'italian', 'french', 'spanish'], name: 'post[languages_attributes][][language]' %>
    <% end %>

This is create post method:

@post= Post.new(post_params)
if @post.save
....

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.

I tried with validates_uniqueness_of :language, scope: :post_id, but if I add two times English (all lowercase), there is no error for this and the data is inserted to the tables.

How to validate uniqueness of the languages for a post with the scope of the current post ?

EDIT: I see that this is a bug in Rails - GitHub, but I still need a solution.

like image 832
gdfgdfg Avatar asked Jan 15 '18 16:01

gdfgdfg


1 Answers

How to validate the uniqueness of two columns in Rails 5? this is answer

validates :username, uniqueness: { scope: :group_id }

if you need records to be unique, add a unique index to records

class AddUniqueIndexToRoles < ActiveRecord::Migration[5.2]
  def change
    add_index :roles, [:username, :group_id], unique: true
  end
end
like image 151
Hany Moh. Avatar answered Sep 18 '22 18:09

Hany Moh.