我有一個高級搜索表單,我想知道如何將用戶選擇保存到數據庫。當前的設置將每次執行的搜索都保存到數據庫中,從而使我能夠統計用戶在網站上搜索的內容。如何將搜索偏好保存到數據庫中
我的問題是我怎麼可以在用戶選擇保存到自己的帳戶,以便預先加載,當他們返回到網站,也可以創建保存的搜索選項列表。我有一個社交網絡應用程序,這將有助於用戶,使他們不必輸入年齡範圍,郵政編碼等,每次他們訪問該網站。
我不知道如何做到這一點。
搜索控制器:
def new
@search = Search.new
end
def create
@search = Search.new(params[:search])
if @search.save
redirect_to @search
else
render 'new'
end
end
def show
@search = Search.find(params[:id])
@users = @search.users
end
搜索模式:
def users
@users ||= find_users
end
private
def find_users
users = User.order(:id)
users = users.where(gender: gender) if gender.present?
users = users.where(zip_code: zip_code) if zip_code.present?
users = users.where(children: children) if children.present?
users = users.where(religion: religion) if religion.present?
users = users.where(ethnicity: ethnicity) if ethnicity.present?
if min_age.present? && max_age.present?
min = [ min_age, max_age ].min
max = [ min_age, max_age ].max
min_date = Date.today - min.years
max_date = Date.today - max.years
users = users.where("birthday BETWEEN ? AND ?", max_date, min_date)
users
end
users
end
end
搜索表單:
<%= form_for @search do |f| %>
<div class="field">
<%= f.label :gender %><br />
<%= f.select :gender, ['male', 'female'], :include_blank => true %>
</div>
<div class="field">
<%= f.label :zip_code %><br />
<%= f.text_field :zip_code %>
</div>
<div class="field">
<%= f.label :children %><br />
<%= f.select :children, [['Yes, they live with me'], ['I want kids now'], ["I want one someday"], ["Not for me"]], :include_blank => true %>
</div>
<div class="field">
<%= f.label :religion %><br />
<%= f.select :religion, [["Agnostic"], ["Atheist"], ["Christian"], ["Catholic"], ["Buddhist"], ["Hindu"], ["Jewish"], ["Muslim"], ["Spiritual without affiliation"], ["Other"], ["None"], ["Prefer not to say"]], :include_blank => true %>
</div>
<div class="field">
<%= f.label :ethnicity %><br />
<%= f.select :ethnicity, [["Asian"], ["Biracial"], ["Indian"], ["Hispanic/Latin"], ["Middle Eastern"], ["Native American"], ["Pacific Islander"], ["White"], ["Other"]], :include_blank => true %>
</div> <%= f.select :min_age, (18..75), :include_blank => true %>
to
<%= f.select :max_age, (18..75), :include_blank => true %>
<div class="actions"><%= f.submit "Search" %></div>
<% end %>