如果您想将静态选项传递给您的选择菜单,您可以简单地传递相应的标记并将 Rails 插入为html_safe
:
<%= select_tag 'Favorite Color', '<option>Blue</option><option>Red</option><option>Yellow</option>'.html_safe %>
编辑:
如果您希望使颜色选项动态且基于模型,那么是的,您可能需要创建一些迁移:
# in console
rails g model color user_id:integer name:string
rake db:migrate
# create some colors in the Rails console
rails console
Color.create(name: 'blue')
Color.create(name: 'red')
Color.create(name: 'yellow')
您没有说要分配favorite_color
给哪个模型,但让我们假设它是User
. 由于用户只能拥有一种最喜欢的颜色,因此您将建立一种has_one
关系:
# app/models/user.rb
class User < ActiveRecord::Base
has_one :color
end
# app/models/color.rb
class Color < ActiveRecord::Base
belongs_to :user
end
您的控制器操作应如下所示:
# app/controllers/users_controller.rb
class UsersController < ApplicationController
def new
@user = User.new
end
def create
@user = User.new(params[:user])
if @user.save
# do something
else
# do something else
end
end
end
最后,您的视图应该类似于以下内容:
# app/views/users/new.html.erb
<%= form_for @user do |f| %>
<!-- whatever other `user` inputs you have -->
<%= f.collection_select :color, Color.all, :id, :name %>
<%= f.submit 'Submit' %>
<% end %>