在我的數據庫中,我有一個用戶表,看起來像:Ruby on Rails的:填充下拉與數據庫記錄的兩個字段
User_ID Firstname Surname Company
1 Steve Jobs Apple
2 Bill Gates Microsoft
我所試圖做的是使一個下拉菜單的形式這將允許用戶選擇他們的名字或他們的公司,例如當Steve Jobs登錄時,他可以在下拉菜單中選擇「Steve」或「Apple」。
我迄今爲止嘗試如下:
<%= f.select :from_name, [session[:user_id],session[:user_id]] %>
這顯然沒有奏效,因爲它只返回登錄用戶的用戶ID。
<%= f.select :from_name, [@user.firstname,@user.company] %>
這給了我零誤差undefined method
姓:NilClass`
我的用戶控制器如下:
class UsersController < ApplicationController
before_filter :check_authorization, :except => [:show, :new, :create, :search ]
def index
@users = User.all
end
def show
@user = User.find(params[:id])
end
def new
@user = User.new
end
def edit
@user = User.find(params[:id])
end
def create
@user = User.new(user_params)
@user.role = "customer"
if @user.save
session[:user_id] = @user.id
# Save a copy of the email address entered by the user into the Accounts table
@account = Account.create(email: params[:user][:primaryemailaddress], user_id: session[:user_id])
redirect_to root_path
else
render 'new'
end
end
def update
@user = User.find(params[:id])
if @user.update(user_params)
redirect_to @user
else
render 'edit'
end
end
def destroy
@user = User.find(params[:id])
@user.destroy
redirect_to users_path
end
private
def user_params
params.require(:user).permit(:title, :firstname, :surname, :housenumber, :street, :city, :postcode, :company, :primaryemailaddress, :password)
end
end
而且我_form.html.erb是:
<%= form_for(@email) do |f| %>
<% if @email.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@email.errors.count, "error") %> prohibited this email from being saved:</h2>
<ul>
<% @email.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<%= f.label :from_name %><br>
<%= f.select :from_name, [current_user.firstname, current_user.company] %>
</p>
<p>
<%= f.label :From_Email_Address %><br>
<%= f.collection_select :account_id, Account.where(user_id: session[:user_id]),
:id,:email %>
</p>
<p>
<%= f.label :to %><br>
<%= f.text_field :to %>
</p>
<p>
<%= f.label :cc %><br>
<%= f.text_field :cc %>
</p>
<p>
<%= f.label :bcc %><br>
<%= f.text_field :bcc %>
</p>
<p>
<%= f.label :subject %><br>
<%= f.text_field :subject %>
</p>
<p>
<%= f.label :message %><br>
<%= f.text_field :message %>
</p>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
我不太清楚如何解決這個問題,有人可以請幫助。對於零
你有沒有定義從控制器的行動@user? –
道歉,我不知道,我剛剛添加了我的控制器 –
爲什麼不使用current_user instaed @user –