Ruby-on-rails 查找数组元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9443375/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 02:54:26  来源:igfitidea点击:

find array element

ruby-on-railsruby

提问by alex

I have an array

我有一个数组

@words = Word.find_all_by_lesson_id(params[:id]) - @user.words

and want to find one element by word_id, something like

并希望通过 word_id 找到一个元素,例如

@current_word = @words[params[:id2].to_i]

where params[:id2]is words.id

这里 params[:id2]words.id

Of course it's wrong, because the arrays index is not the same as words.id, so how can I do it correct?

当然是错误的,因为数组索引与 不一样words.id,那么我该怎么做才能正确呢?

OR

或者

can you advice me on how to work with the model if I want to exclude some records from it?

如果我想从中排除一些记录,你能就如何使用模型提出建议吗?

回答by megas

@current_word = @words.detect{|w| w.id == params[:id2]}