【发布时间】:2018-09-24 17:10:29
【问题描述】:
我是 ROR 的新手。我在下面创建的查询运行正常。我正在准备审讯。但我没有成功。查询如下;
@rad_user_group.groupname = SELECT groupname FROM radgrs INNER JOIN nas WHERE radgrs.grdefault = true AND radgrs.tenant_id = nas.tenant_id AND nas.realipaddr = "192.168.22.175" AND nas.active = true
如何在另一个问题中为以下查询创建 switch case?如果查询失败,则返回 NULL。
感谢您的关心。
def realipaddr
request.remote_addr
end
def create
@rad_check = RadCheck.new(rad_check_params)
@rad_check.tenant_id = Na.find_by(realipaddr: realipaddr, active: :true).tenant_id
respond_to do |format|
if @rad_check.save
format.html { redirect_to @rad_check, notice: 'Rad check was successfully created.' }
format.json { render :show, status: :created, location: @rad_check }
else
format.html { render :new }
format.json { render json: @rad_check.errors, status: :unprocessable_entity }
end
end
end
RadCheck 模型
class RadCheck < ApplicationRecord
has_one :rad_user_group, dependent: :destroy
after_initialize :add_rad_user_group
before_save :set_radcheck
def add_rad_user_group
self.rad_user_group ||= RadUserGroup.new if self.new_record?
end
def set_radcheck
self.rad_user_group.username = username
self.op = ":="
self.attribu = "Cleartext-Password"
end
end
class CreateRadChecks < ActiveRecord::Migration[5.2]
def change
create_table :rad_checks do |t|
t.integer :tenant_id
t.string :username
t.string :password
t.string :attribu
t.string :op
t.string :realipaddr
t.string :groupname
t.timestamps
end
end
end
Radgr 模型
class Radgr < ApplicationRecord
end
class CreateRadgrs < ActiveRecord::Migration[5.2]
def change
create_table :radgrs do |t|
t.integer :tenant_id
t.string :groupname
t.string :realipaddr
t.boolean :grdefault
end
end
end
RadUserGroup 模型
class RadUserGroup < ApplicationRecord
belongs_to :rad_check
end
class CreateRadUserGroups < ActiveRecord::Migration[5.2]
def change
create_table :rad_user_groups do |t|
t.integer :tenant_id
t.string :username
t.string :groupname
t.references :rad_check, foreign_key: true
t.timestamps
end
end
end
Na模型
class Na < ApplicationRecord
end
class CreateNas < ActiveRecord::Migration[5.2]
def change
create_table :nas do |t|
t.integer :tenant_id
t.string :nasname
t.string :realipaddr
t.boolean :active
end
end
end
【问题讨论】:
-
您的模型和关联是什么?您的原始查询正在返回一组记录,并且您将其分配给一个 id,看起来您缺少诸如“LIMIT 1”之类的内容或仅获得第一个。通过适当的关联,您可以执行以下操作:
Radgrs.joins(:nas).where(nas: {realipaddr: '1292...'}).first但我只是猜测,您没有展示您的模型。
标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5