如何制作一个下拉菜单,反映数据库中相应列中存储的内容?
我有一个性别选择的下拉菜单,它可以更新数据库 但是在刷新的选择菜单中返回默认选项,因为我的所有文本字段都正在提取数据库数据。
<%= form_for @profile, :remote => true, do |f| %>
Username: <%= @profile.user.username %><br />
URL: http://site.com/<%= @profile.user.username %><br />
First Name: <%= f.text_field :first_name, %><br />
Last Name: <%= f.text_field :last_name, %><br />
I am: <%= f.select :gender, options_for_select([['Select Gender', ''],['Male','m'],['Female','f']]) %><br />
<%= f.submit 'update' %><br />
<% end %>
任何线索我错过了什么? 亲切的问候
这是我的模特:
class Profile < ActiveRecord::Base
belongs_to :user
attr_accessible :first_name, :last_name, :gender, :motd
# Local Variables
# Regex Variables
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
alpha_regex = /^[a-zA-Z]*$/
alpha_numeric_regix = /^[a-zA-Z0-9_]*$/
#Form Validation
validates :first_name, :presence => true,
:length => { :minimum => 2, :maximum => 15 },
:format => {
:with => alpha_regex,
:message => "Your first name must contain letters only"
}
validates :last_name, :presence => true,
:length => { :minimum => 2, :maximum => 15 },
:format => {
:with => alpha_regex,
:message => "Your last name must contain letters only"
}
validates :gender, :presence => true,
:inclusion => {
:in => %w( m f ), :message => "Are you male or female?"
}
end
从控制器更新方法
def update
respond_to do |format|
if @profile.update_attributes(params[:profile])
format.js { render :js => "window.location = '#{settings_edit_profile_path}'" }
flash[:success] = "Profile updated"
else
format.js { render :form_errors }
end
end
end
答案 0 :(得分:1)
options_for_select具有选择值的特殊语法:
<%= f.select :gender, options_for_select([['Select Gender', ''],['Male','m'],['Female','f']], "#{@profile.gender}") %>
可能会像您期望的那样工作。
或者您可以创建一个Gender模型并使用collection_select默认执行此操作:
<%= f.collection_select :gender, Gender.all, :value, :description, :prompt => true %>