您好我正在尝试一些元编程并且卡住了。我希望通过一系列具有名称和可能是id
的哈希来获得许多关联# what I would like to get is
user.projects.find(project.id).comments
# and or
user.projects.find(project.id).comments.find(comment.id)
# using the array of hashes called a_h -> array_of_hashes
# I am stuck and am looking for some guidance.
# gem install mongoid
require 'mongoid'
begin
Mongoid.load!("mongoid.yml", :development)
rescue
Mongoid.load!("config/mongoid.yml", :development)
end
class User
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
has_many :projects
end
class Project
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
belongs_to :user
has_many :comments
end
class Comment
include Mongoid::Document
include Mongoid::Timestamps
field :name, type: String
belongs_to :project
end
user = User.create( name: :user )
project = user.projects.create( name: :project )
comment = project.comments.create( name: :comment )
comment = project.comments.create( name: :comment )
comment = project.comments.create( name: :comment )
comment = project.comments.create( name: :comment )
a_h = [
{ name: 'users', id: user.id, position: 0 },
{ name: 'projects', id: project.id, position: 1 },
{ name: 'comments', id: nil, position: 2 },
]
# or comment with id
a_h = [
{ name: 'users', id: user.id, position: 0 },
{ name: 'projects', id: project.id, position: 1 },
{ name: 'comments', id: comment.id, position: 2 },
]
# this works but would like to be able to itterate over projects a_h[1] and comments a_h[2]
user.send( a_h[1][ :name ].to_sym, "find( '#{a_h[1][ :id ]}' )" )
scope = User.scoped( {} )
scope = scope.scoped.where( id: user.id) # .last but doesn't work with projects
scope = scope.projects.where( id: project.id)
# what I would like to get is
user.projects.find(project.id).comments
# and or
user.projects.find(project.id).comments.find(comment.id)
user.send( a_h[1..-1].map { |h|
[ h[ :name ], "find( '#{ h[ :id ] }' )" ] if h[ :id ].present?
h[ :name ] if h[ :id ].blank?
} )
a_h[1..-1].map { |h| [ h[ :name ], "find( '#{ h[ :id ] }' )" ] }.flatten
a_h[1..-1].map { |h| h[ :name ], "find( '#{ h[ :id ] }' )" } # doesn't work without array
答案 0 :(得分:1)
res = user
a_h[1..-1].each do |h|
res = res.send(h[:name]).send('find', h[:id]) if h[:id]
end
puts res