在Rails 4中使用f.select保存多个记录

时间:2014-11-05 11:49:38

标签: ruby-on-rails ruby-on-rails-4

我有一个名为Professor的模型,其中包含以下内容:

class Professor < ActiveRecord::Base
  enum language: [:spanish, :english, :french]
end

我希望能够为每个Professor分配多种语言,因此我的表单中包含以下代码:

<%= f.select(:language, options_for_select(Professor.languages.keys.map {|language| [language.titleize, language]}), {}, { multiple: true }) %>

如果我选择所有三个选项,我会从服务器

获得以下内容
"language"=>["", "spanish", "english", "french"]

但在控制台中我得到了:

Professor Load (0.7ms)  SELECT  "professors".* FROM "professors"   ORDER BY "professors"."id" ASC LIMIT 1
=> #<Professor id: 1, language: nil>

这里有什么问题,是否有更好的方法来解决它?

1 个答案:

答案 0 :(得分:0)

language列的serialize或(首选方式)可以创建多对多关联:

# professor.rb
class Professor < ActiveRecord::Base
  has_many :professor_languages, dependent: :destroy
  has_many :languages, through: :professor_languages
end

# form:
<%= f.select(:language_ids, options_for_select(Language.all.map {|language| [language.titleize, language.id]}), {}, { multiple: true }) %>

language删除Professor列并创建包含必要迁移的ProfessorLanguageLanguage个模型。