0

我是 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
4

1 回答 1

0

使用 find_or_create_by_name 解决了它。

类主机'Systemadmin',:foreign_key => 'primary_sadmin_id'
  belongs_to :secondary_sadmin, :class_name => 'Systemadmin', :foreign_key => 'secondary_sadmin_id'
  has_many :database, :class_name => '主机'


  def sa_name1
    primary_sadmin.try(:sa_name1)
  结尾

  def sa_name1=(sa_name1)
    self.primary_sadmin = Systemadmin.find_or_create_by_name(sa_name1) 如果 sa_name1.present?
  结尾

  def sa_name2
    secondary_sadmin.try(:sa_name2)
  结尾

  def sa_name2=(sa_name2)
    self.secondary_sadmin = Systemadmin.find_or_create_by_name(sa_name2) 如果 sa_name2.present?
  结尾

结尾

于 2013-04-23T16:55:39.120 回答