Rails: limit enum column for already submitted values

In my rails app I have 2 models: post and post_translations.

class PostTranslation < ActiveRecord::Base
  belongs_to :post

  LANGUAGES = %w( en fr es de it )
  validates_inclusion_of :language, :in => LANGUAGES

end

class Post < ActiveRecord::Base
  has_many :post_translations

end

I want to prevent the same language translation from being submitted twice, so I want to limit the enums to the values not listed in the language column of a particular post_id. I don't know if I should do this in model, controller or helper. Which is the best practice?

Thanks in advance.

Answers


I'd use an attribute on the class instead of defining it on an instance.

class PostTranslation < ActiveRecord::Base
  @@languages = %w( en fr es de it )
  cattr_reader :languages

  belongs_to :post

  validates :language, :inclusion => { :in => @@languages },
    :uniqueness => { :scope => :post_id }
end

Now to fulfill your requirement of showing only the languages without translations, define a method on Post:

class Post < ActiveRecord::Base
  has_many :post_translations

  def untranslated
    PostTranslation.languages - post_translations.map(&:language)
  end
end

Then you can build a select menu by getting a post (@post = Post.find(params[:id]) and populating the collection from @post.untranslated.


Need Your Help

JPA testing UniqueConstraint

testing jpa playframework constraints

I would like to test UniqueConstraint in JPA/Playframework:

DIV must always define display and position or not or what is default

html css html5 css3 sass

After searching a lot I cannot find the answer I am looking for. I am a TABLE user currently editing my old site to new tech but I have a question:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.