Rails 3 f.select设置为使用Ransack在搜索表单中使用

tva*_*nt2 3 select ruby-on-rails-3

提前为初学者问题道歉,但由于我是初学者,所以:在我的Rails 3应用程序中,我的Profile模型属性为:subject.在我的表单中,我有以下代码供用户分配:subject:

<%= f.select :profile_subject, options_for_select([['Select', 0], ['Arts', 1], ['Biology', 2], ['Business', 3], ['Chemistry', 4], ['English', 5], ['Foreign Language', 6], ['Government', 7], ['Health', 8], ['History', 9], ['Math', 10], ['Physics', 11], ['Vocational', 12]]) %>
Run Code Online (Sandbox Code Playgroud)

我想将:subject字符串用于两件事:

  1. 在我的视图中渲染
  2. 在搜索表单中使用(我正在使用Ransack进行搜索)

我认为我没有在我的数据库(或构建表单)中正确设置它,因为我似乎只存储id("ex:1")而不是字符串("ex:Arts").在我删除选项ID之前,我很好奇:对于这样的事情,在选择中包含选项ID和字符串是否被认为是一种好习惯?或者删除id并仅将其保存为字符串数组?

询问所有这些的原因是关于我的搜索表单.正如我所提到的,我正在使用Ransack,而我只是不确定如何f.select使用一堆字符串来完成工作.

tva*_*nt2 7

首先,我没有在我的数据库中正确设置它.所以我更正了表格,因此:subject存储的是一个字符串.这是新表格:

<%= f.select :subject, options_for_select([['Select', ''], ['Arts'], ['Biology'], ['Business'], ['Chemistry'], ['English'], ['Foreign Language'], ['Government'], ['Health'], ['History'], ['Math'], ['Physics'], ['Vocational']], :selected => @profile.subject) %>
Run Code Online (Sandbox Code Playgroud)

然后,对于搜索表单,我只需要添加一个谓词_eq:

<%= f.select :profile_subject_eq, options_for_select([['Select', ''], ['Arts'], ['Biology'], ['Business'], ['Chemistry'], ['English'], ['Foreign Language'], ['Government'], ['Health'], ['History'], ['Math'], ['Physics'], ['Vocational']], :selected => :profile_subject) %>
Run Code Online (Sandbox Code Playgroud)

现在它有效.