0

您将如何实现基于请求模型搜索表​​的方法?

我有一个 User 和 Vehicle 表,它们都是存储在 Equipment 表中的分配设备。我正在尝试使用相同的方法显示分配给用户和车辆的设备。Equipment 表有一个 user_id 和 vehicle_id 显示设备分配到的位置。

有什么方法可以传入一个表变量(可以是用户或车辆),然后将该变量 ID:作为搜索条件,以便根据正在查看的显示页面显示分配给用户或车辆的设备 -

def equip(table, id)
  equip = Equipment.where(table_id: id)
end

这样传入的表变量替换了where()方法的“表”部分,使其成为user_id或vehicle_id?

4

2 回答 2

1

正如 Yoshiji 先生所说,这是可能的,但我强烈建议您研究多态关联

于 2013-04-29T21:30:52.267 回答
0

对的,这是可能的:

def equip(table, id)
  equip = Equipment.where("#{table}_id = ?", id)
end

但这可能会很快导致错误,请在之前添加一些检查内容:

def equip(table, id)
  if self.columns.map(&:name).include?("#{table}_id")
    equip = Equipment.where("#{table}_id = ?", id)
  else
    # the columns does not exists!
  end
end

解释:

self.columns.map(&:name) # returns the name of all the columns of the model in a array

我的 Rails 控制台示例:

User.columns.map(&:name)
=> ["id", "username", "profession_id", "external_reference", "authorisation_group", "created_at", "updated_at", "active", "license", "visible"]
于 2013-04-29T21:26:10.267 回答