[英]Rails Active Record, how to have an additional field parameter in the result of a query?
I actually have this model: 我实际上有这个模型:
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
the method all_join_wisp does almost what I want, it adds the field wisp_name, except it return a hash and not an active record object. 方法all_join_wisp几乎做了我想要的,它添加了字段wisp_name,除了它返回一个哈希而不是一个活动的记录对象。
Is there a way to retrieve an active record object instead? 有没有办法检索活动记录对象?
The Role model does not have belongs_to and the wisp model does not have has_many :roles , I guess it was done for flexibility or something (I did not develop the application I'm working on). Role模型没有belongs_to,而wisp模型没有has_many:roles,我想这是为了灵活性或其他东西(我没有开发我正在开发的应用程序)。
Solution implemented here: https://github.com/nemesisdesign/OpenWISP-Geographic-Monitoring/blob/287861d95fffde35d78b76ca1e529c21b0f3a54b/app/models/role.rb#L25 Thanks to @house9 解决方案在这里实现: https : //github.com/nemesisdesign/OpenWISP-Geographic-Monitoring/blob/287861d95fffde35d78b76ca1e529c21b0f3a54b/app/models/role.rb#L25感谢@ house9
you can use find_by_sql
- you get back what looks like an activerecord object but isn't really, it will have attributes from your query but they will all be string data types instead of the real types, often this is ok 你可以使用
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
then 然后
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
model 模型
class Role < ActiveRecord::Base
def self.do
joins("LEFT JOIN wisps w ON
w.id = roles.id").select("roles.*,
wisps.name AS wisp_name")
end
end
controller 调节器
@roles = Role.do
@wisps = @roles.map {|i| i.wisp_name}
view 视图
<%= @wisps %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.