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

时间:2011-11-25 07:28:29

标签: ruby-on-rails-3 select

提前为初学者问题道歉,但由于我是初学者,所以:在我的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]]) %>

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

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

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

2 个答案:

答案 0 :(得分: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) %>

然后,对于搜索表单,我只需要添加一个谓词_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) %>

现在它有效。

答案 1 :(得分:1)

由于多种原因,我会在模型中存储主题数组。您可以将其用于验证。

class Profile < ActiveRecord::Base
  SUBJECT_VALUES = %w( Arts Biology Business Chemistry English Foreign\ Language Government Health History Math Physics Vocational )
  validates_inclusion_of :subject, :in => SUBJECT_VALUES
end

您的新/编辑表单可以轻松使用它。

<%= f.select :subject, Profile::SUBJECT_VALUES %>

和您的搜索表单。

<%= f.select :profile_subject_eq, Profile::SUBJECT_VALUES %>

如果你想允许多个选择进行搜索。

<%= f.collection_select :profile_subject_in, Profile::SUBJECT_VALUES, :to_s, :to_s, {}, { :multiple => true } %>