0
我试图把结果从我的投票模型在哈希进一步的用法,但我不知道如何从Ruby中的变量创建一个哈希键。见下面的例子:Rails模型结果哈希变量作为一个关键问题
def create_hash_array(campaign_votes)
target_hash = Hash.new
campaign_votes.each_with_index do |cv,i|
target_hash[cv.content_id] = {} if i == 0
if target_hash[cv.content_id].member?(cv.vote_button_id)
target_hash[cv.content_id][cv.vote_button_id] = (target_hash[cv.content_id][cv.vote_button_id]).to_i + 1
else
target_hash[cv.content_id] = {cv.vote_button_id => nil}
end
end
target_hash
end
通常我得到了一个错误:
undefined method `member?' for nil:NilClass
,但它来自无法识别target_hash[cv.content_id]
,我怎样才能使不被认可target_hash[cv.content_id]
变量?
错误很明显,因为'target_hash [cv.content_id]'试图从密钥'cv.content_id'获取哈希值,该密钥尚未设置,并且为零,并且您正在对其调用'member'。基本上,你是否想用'cv.vote_button_id'键嵌套你的散列,如果它存在的话? –