由于 Ruby 非常棒,可以使用任何对象作为键
document = Document.find 1
o = Hash.new
o[1] = true
o[:coool] = 'it is'
o[document] = true
# an it works
o[document]
#=> true
但仅仅因为它是可能的并不意味着是好的做法
但是我有一种情况,在我的控制器中我需要设置类似的东西,所以我可以在视图中循环遍历它
#controller
@users_with_things = Hash.new
Things.accessible_by(some_curent_user_logic).each do |thing|
@user_with_things[thing.user] ||= Array.new
@user_with_things[thing.user] << thing.id
end
#view
- @users_with_things.each do |user, thing_ids|
%input{type: :checkbox, name: "blank[user_#{user.id}]", value: 1, class: "select_groups", :'data-resource-ids' => "[#{thing_ids.join(',')}]", :'data-user-type' => user.type }
我之所以要这样做是因为我不想从我的角度来看User.find_by_id
(想让它变得干净)
#controller
@users_with_things = Hash.new
Things.accessible_by(some_curent_user_logic).each do |thing|
@user_with_things[thing.user.id] ||= Array.new
@user_with_things[thing.user.id] << thing.id
end
#view
- @users_with_things.each do |user_id, thing_ids|
- user = User.find user_id
%input{type: :checkbox, name: "blank[user_#{user.id}]", value: 1, class: "select_groups", :'data-resource-ids' => "[#{thing_ids.join(',')}]", :'data-user-type' => user.type }
所以我的第一个问题是:在这种情况下可以使用 ActiveRecord 对象作为哈希键吗
我可以想象几种可能出错的场景(会话、模型中的对象更改等),但这只是为了在视图中呈现
选择 !
所以这是一种方法,另一种可能是这样
#controller
@users_with_things = Hash.new
Things.accessible_by(some_curent_user_logic).each do |thing|
@user_with_things[thing.user.object_id] ||= Array.new
@user_with_things[thing.user.object_id] << thing.id
end
#view
- @users_with_things.each do |user_object_id, thing_ids|
- user = ObjectSpace._id2ref(user_object_id) #this will find user object from object_id
%input{type: :checkbox, name: "blank[user_#{user.id}]", value: 1, class: "select_groups", :'data-resource-ids' => "[#{thing_ids.join(',')}]"", :'data-user-type' => user.type }
……更重要的是,铁杆。但是,如果出于某种原因hash[ARobject] = :something
会由于某种原因创建大内存集群,那是一种解决方法
问题2:这样做是个好主意吗?
要完整,还有另一种选择,那就是
# ...
@user_with_thing[ [thing.user.id, thing.user.type] ] << thing_id
# ...
所以基本上数组对象将是关键
@user_with_thing[ [1, 'Admin'] ]
#=> [1,2,3]