我实际上有这个模型:
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/