我有一个名为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>
这里有什么问题,是否有更好的方法来解决它?
答案 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
列并创建包含必要迁移的ProfessorLanguage
,Language
个模型。