Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/57.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 需要像数组一样遍历rails数据库的实例_Ruby On Rails - Fatal编程技术网

Ruby on rails 需要像数组一样遍历rails数据库的实例

Ruby on rails 需要像数组一样遍历rails数据库的实例,ruby-on-rails,Ruby On Rails,我在rails数据库中有一个关系,我得到了一个关系实例。然后,我需要确定该实例的填充量。我通过计算关系中的零来实现这一点,但我不知道如何通过代码实现这一点。我知道。每个循环,但这使我声明字段,我需要更像数组的东西。这就是我目前所拥有的 @survey_data = Surveyprofile.find_by(:user_id => @user.user_id) @counter = 0 @index = 0 @survey_data.each do |d| //i need som

我在rails数据库中有一个关系,我得到了一个关系实例。然后,我需要确定该实例的填充量。我通过计算关系中的零来实现这一点,但我不知道如何通过代码实现这一点。我知道。每个循环,但这使我声明字段,我需要更像数组的东西。这就是我目前所拥有的

@survey_data = Surveyprofile.find_by(:user_id => @user.user_id)

@counter = 0
@index = 0
@survey_data.each do |d|
   //i need something like

   if d[index].nil? == false
          @counter = @counter +1
       end
   @index++
 end
有人知道如何表达这个吗??
(顺便说一句,这都是在控制器中完成的)

我还没有测试过这种方法,但它应该可以工作

survey\u profile.rb:

class SurveyProfile < ActiveRecord::Base

  def self.number_of_empty_answers(user_id)
    user_survey = SurveyProfile.find_by_user_id(user_id)
    count = 0
    user_survey.attributes.each do |attr_name, attr_value|
      count += 1 if attr_value.nil?
    end
    return count
  end
SurveyProfile.number_of_empty_answers(@user.id)
class方法
number\u of\u empty\u answers
统计用户尚未填写的答案。然后从控制器调用该方法

请注意,它不必是类方法。它也可以是一个实例方法。您可以首先在控制器中找到实例,然后对其调用方法


由于您正在遍历attributes散列,因此您可以获得更多的想象力并构建一个字段名数组,这些字段名不是空的。但是如果你只是想计算一下,上面的方法应该是有效的。

如果你是根据有多少关系来计算一些东西(如果关系为零?或者不是),我认为
@pp.count
会有效。首先
index++
在Ruby上不起作用,试试
index+=1
,其次,你能再努力一点来描述你的问题吗?我得到一个错误,说没有方法“计数”。对于将来的使用,我将如何进行,比如说计算包含特定值的字段的数量?您到底想做什么?如果您使用有意义的变量名,这会有所帮助。像
@pp
这样的东西对你以外的人来说没有任何意义。更重要的是,用户正在填写调查,我需要显示用户填写了多少。我需要数一数有多少字段输入了数据。嘿,这很有效,非常感谢。这个社区触礁了。