两个belongs_to相同的模型使用名称分配id

时间:2013-03-26 20:28:12

标签: ruby-on-rails associations has-many belongs-to

我是RoR的新手,正致力于创建数据库。每个主机都有两个系统管理员。我试图将创建主机时给出的名称与其各自的系统管理员关联起来。我该怎么做呢?

如果用户输入系统管理员的名称,那么如何使用该名称获取ID并将该ID插入primary_sadmin_id字段?

Systemadmin.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

host.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

host_controller.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

schema.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

1 个答案:

答案 0 :(得分:0)

使用find_or_create_by_name解决它。

class Host  'Systemadmin', :foreign_key => 'primary_sadmin_id'
  belongs_to :secondary_sadmin, :class_name => 'Systemadmin', :foreign_key => 'secondary_sadmin_id'
  has_many   :database, :class_name => 'Host'


  def sa_name1
    primary_sadmin.try(:sa_name1)
  end

  def sa_name1=(sa_name1)
    self.primary_sadmin = Systemadmin.find_or_create_by_name(sa_name1) if sa_name1.present?
  end

  def sa_name2
    secondary_sadmin.try(:sa_name2)
  end

  def sa_name2=(sa_name2)
    self.secondary_sadmin = Systemadmin.find_or_create_by_name(sa_name2) if sa_name2.present?
  end

end