Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何正确获取数组项?_Ruby On Rails_Arrays - Fatal编程技术网

Ruby on rails 如何正确获取数组项?

Ruby on rails 如何正确获取数组项?,ruby-on-rails,arrays,Ruby On Rails,Arrays,我向数据库提出了这个请求 @show = Question.where(:question_status => params[:id]) 然后在@show变量中我有这样一个:[#,#,#] 例如,如何获取问题字段? 我正在尝试@show.question,但出现错误没有定义方法问题 @show = Question.find_by_question_status(params[:id]) and @show.question 如果您使用where语句,请使用: @show.each

我向数据库提出了这个请求

@show = Question.where(:question_status => params[:id])
然后在@show变量中我有这样一个:
[#,#,#]

例如,如何获取问题字段? 我正在尝试
@show.question
,但出现错误
没有定义方法问题

 @show = Question.find_by_question_status(params[:id]) 
and @show.question
如果您使用where语句,请使用:

@show.each do |show|
  show.question
end

@show是一个ActiveRecord::关系对象(数组)。它不属于问题类

@show = Question.where(:question_status => params([:id]).first

如果您只期望一个结果。否则,您必须迭代每个元素的数组

在rails控制台上尝试此代码

@show = Question.where(:question_status => params[:id])
@show.each_with_index do |ques, index|
   p "#{index+1} :: #{ques.question}"
end

在索引的帮助下,您将获得行的序列号。

您想获取所有问题字段的数组吗

questions = Question.where(:question_status => params[:id]).map(&:question)
然后你就可以像

questions.each{|question| puts question }
使用
@show.map(&:question)
。这将为您提供数组中的所有问题

@show.question向您提供错误-没有定义的方法问题,因为您试图在数组@show上操作question

如果你做了
@show.first.question
,它会给你第一个对象的问题

如果您执行
@show.map(&:question)
操作,它将为您提供一系列问题

获取所有信息

@show.each do |show|
  puts show.question
  puts show.question_status
  puts show.user_id
end

您可以根据需要对其进行优化。

您使用的是哪个数据库?如果您需要客户端…MySQL,您想获取问题表中所有问题字段的数组吗?查看我的答案。请尝试我的解决方案,它可能会帮助查找方法只能通过id或其他东西进行搜索?抱歉。当他在params中传递id时,他以为他在寻找id。请参阅我编辑的答案它仅提供数组中的最后一项,该项在此问题中通过show=question再次进行后检查。通过“问题”状态(参数[:id])和show.questionyes以及其他信息查找。我可以像这样使用
map(&:question)
map(&:question,&status)
?不,你不能那样使用。你想同时获取状态字段吗?我想获取数组信息,然后从中获取所有我想要的信息,例如:问题和状态字段或仅问题字段..是的…它会为我提供任何字段…但仅针对数组中的一项。当我通过params[:id]搜索时,它是类别的id,在数组中,我从该类别中获取所有信息。你的解决方案只给了我一个项目。我想我应该在每个项目中使用每个项目