ruby-on-rails - Rails Active Record,如何在查询结果中添加附加字段参数?

标签 ruby-on-rails ruby-on-rails-3 activerecord openwisp

我实际上有这个模型:

class Role < ActiveRecord::Base
  acts_as_authorization_role

  def self.all_join_wisp
    self.connection.select_all("SELECT roles.*, wisps.name AS wisp_name FROM roles LEFT JOIN wisps ON wisps.id = roles.authorizable_id")
  end
end

方法 all_join_wisp 几乎满足了我的要求,它添加了字段 wisp_name,只不过它返回一个哈希值而不是事件记录对象。

有没有办法检索事件记录对象?

角色模型没有belongs_to,wisp模型没有has_many:roles,我想这是为了灵活性或其他原因(我没有开发我正在开发的应用程序)。

编辑:已实现的解决方案

此处实现的解决方案:https://github.com/nemesisdesign/OpenWISP-Geographic-Monitoring/blob/287861d95fffde35d78b76ca1e529c21b0f3a54b/app/models/role.rb#L25 感谢@house9

最佳答案

你可以使用find_by_sql - 你会得到看起来像activerecord对象但实际上不是的东西,它会具有来自你的查询的属性,但它们都是字符串数据类型而不是真实类型,通常这样就可以了

def self.all_join_wisp
  self.find_by_sql("SELECT roles.*, wisps.name AS wisp_name FROM roles LEFT JOIN wisps ON wisps.id = roles.authorizable_id")
end

然后

list = Role.all_join_wisp
list.each do |x|
  puts x
  puts x.inspect
  puts x.id # the role id 
  puts x.id.is_a?(Integer) # false
  puts x.id.is_a?(String) # true
  puts x.name # the role name
  puts x.wisp_name # wisp name, NOTE: Role does not really have this attribute, find_by_sql adds it
end

关于ruby-on-rails - Rails Active Record,如何在查询结果中添加附加字段参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15483639/

相关文章:

sql - 如何在 Rails 中查找 jsonb 中的哈希键?

ruby-on-rails-3 - Rails 3 - 使文本字段仅接受数字值

ruby-on-rails-3 - 事件记录查询数组字段中的值

ruby-on-rails - 如何预先加载嵌套的多态关联

ruby-on-rails - Rails 3 中的 onchange remote_function - 有效吗?我怎样才能不引人注目地完成它?

python - Rails 模型继承

ruby-on-rails - 如何根据 Rails 中的外键列选择唯一记录?

ruby-on-rails-3 - ActiveAdmin - 使资源索引显示 'edit' 和 'delete' 但不显示 'view'

mysql - 如何使用 Codeigniter 对组中的项目进行计数?

ruby-on-rails - 如何保存用户注册日期[rails]