我想将数据从db表填充到Rails 4.1中的下拉列表。
#controller code:
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
def index
@users = User.all
end
def show
end
def new
@user = User.new
end
def edit
end
def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def update
respond_to do |format|
if @user.update(user_params)
format.html { redirect_to @user, notice: 'User was successfully updated.' }
format.json { render :show, status: :ok, location: @user }
else
format.html { render :edit }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
def destroy
@user.destroy
respond_to do |format|
format.html { redirect_to users_url, notice: 'User was successfully destroyed.' }
format.json { head :no_content }
end
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:first_name, :last_name, :country)
end
end
#view code:
<%= f.select :country, @user%>
当我使用上面的代码时,我收到错误
&#34;未定义的方法`空?&#39;为零:NilClass&#34;
这个问题的解决方案是什么?
答案 0 :(得分:0)
我已经尝试了以下代码并且工作正常:
<%= f.select :country, User.all.collect {|user| [ user.country, user.country ] } %>