我是 RoR 的新手,正在创建一个数据库。每个主机有两个系统管理员。我试图将创建主机时给定的名称与其各自的系统管理员相关联。我该怎么做呢?
如果用户输入系统管理员的名称,那么我如何使用该名称获取 id 并将该 id 插入 primary_sadmin_id 字段?
系统管理员.rb
class Systemadmin < ActiveRecord::Base
attr_accessible :id, :email, :location, :name, :netid, :priphone, :secphone
has_many :primary_sysadmin, :class_name => 'Host', :foreign_key => 'primary_sadmin_id'
has_many :seconday_sysadmin, :class_name => 'Host', :foreign_key => 'seconary_sadmin_id'
end
主机.rb
class Host < ActiveRecord::Base
attr_accessible :iogroup, :ip, :location, :name, :opsystem, :primary_sadmin_id, :purpose, :secondary_sadmin_id, :host_type
belongs_to :primary_sadmin, :class_name => 'Systemadmin', :foreign_key => 'primary_sadmin_id'
belongs_to :secondary_sadmin, :class_name => 'Systemadmin', :foreign_key => 'secondary_sadmin_id'
end
主机控制器.rb
def create
@host = Host.new(params[:host])
@host.primary_sadmin_id = Systemadmin.find_by_name(:sa_name1)
@host.secondary_sadmin_id = Systemadmin.find_by_name(:sa_name2)
respond_to do |format|
if @host.save
format.html { redirect_to @host, notice: 'Host was successfully created.' }
format.json { render json: @host, status: :created, location: @host }
else
format.html { render action: "new" }
format.json { render json: @host.errors, status: :unprocessable_entity }
end
end
end
架构.rb
create_table "hosts", :force => true do |t|
t.string "name"
t.integer "ip", :precision => 38, :scale => 0
t.string "location"
t.string "host_type"
t.string "opsystem"
t.string "iogroup"
t.integer "primary_sadmin_id", :precision => 38, :scale => 0
t.integer "secondary_sadmin_id", :precision => 38, :scale => 0
t.string "purpose"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "systemadmins", :force => true do |t|
t.string "name"
t.string "netid"
t.integer "priphone", :precision => 38, :scale => 0
t.integer "secphone", :precision => 38, :scale => 0
t.string "email"
t.string "location"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end