Ruby on rails Rails:限制已提交值的枚举列

Ruby on rails Rails:限制已提交值的枚举列,ruby-on-rails,ruby-on-rails-3,enums,model,associations,Ruby On Rails,Ruby On Rails 3,Enums,Model,Associations,在我的rails应用程序中,我有两个模型:post和post_翻译 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_t

在我的rails应用程序中,我有两个模型:post和post_翻译

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
class PostTranslation语言的包含
结束
类Post
我希望防止两次提交同一语言翻译,因此我希望将枚举限制为特定post_id的语言列中未列出的值。
我不知道我应该在model、controller还是helper中执行此操作。
哪一个是最佳实践


提前感谢。

将此保存在模型中是完全有效的。模型应承担确保输入数据正确的主要责任

对于您的特定情况,您可以使用
:university
验证器,并将范围传递给它。基本上,您的验证将确保语言在特定帖子的上下文中是唯一的

以下方面应起作用:

validates :language, :inclusion => { :in => LANGUAGES },
                     :uniqueness => { :scope => :post_id }
如果您喜欢Rails 2样式的语法,可以使用:

validates_uniqueness_of :language, :scope => :post_id

我会在类上使用属性,而不是在实例上定义它

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
class PostTranslation{:in=>@@languages},
:唯一性=>{:范围=>:post_id}
结束
现在,为了满足只显示语言而不显示翻译的要求,请在Post上定义一个方法:

class Post < ActiveRecord::Base
  has_many :post_translations

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

然后,您可以通过获取post(
@post=post.find(params[:id]
)来构建一个选择菜单并从
@post.untranslated

填充集合。好的,这将阻止记录被保存,但在我的选择列表中,我仍然可以选择所有语言:如何隐藏已提交的语言?我想这需要一个列名,所以
:scope=>:post\u id
不是我,我想你可能可以在类似于
LANGUAGES-@post.post_translations.all.map{{pt{pt.language}
的助手。