2011-11-25 44 views
3

對於初學者的問題提前道歉,但因爲我是一個初學者在這裏去:在我的Rails 3應用程序,我有我的Profile模型的屬性:subject。在我的形式,我有用戶將下面的代碼來分配:subjectRails 3 f.select設置爲在搜索表單中使用使用Ransack

<%= 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. 要在搜索表單中使用(我正在使用進行搜索)

我不認爲我在我的數據庫中設置了它(或者構建了表單)正確,因爲我似乎只存儲了id(「ex:1」)而不是字符串(「ex:Arts」)。然而,在我刪除選項ID之前,我很好奇:對於這樣的事情,在選擇中包含選項ID和字符串是否被認爲是很好的做法?或剝離身份證,只保留它作爲一個字符串數組?

問這一切的原因是關於我的搜索表單。正如我所提到的,我正在使用Ransack,而且我不確定如何使f.select只用一堆字符串。

回答

7

首先,我沒有在我的db中正確設置它。所以我糾正了表格,所以:存儲的主題是一個字符串。這裏的新形式:

<%= 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

特拉維斯,這只是爲我解決了它。很高興看到你仍在幫助我! – fakefarm

+0

哦,嘿!任何時候,男人! – tvalent2

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 } %> 
+0

謝謝,我會試試看!我遇到的一件事是當我選擇一個選項並且搜索表單提交時,'subject'值返回到「Select」,而不是顯示的值。你知道那裏會發生什麼嗎? – tvalent2

+0

@ tvalent2你在尋找哪一個搜索表單? 「f.select:subject」用於新建/編輯。 – graywh