Rails嵌套。每个都无法访问顶级变量

时间:2017-03-24 23:51:20

标签: ruby-on-rails each ruby-on-rails-5

此代码在我保存新挑战时执行,然后循环遍历所有关联用户并为挑战中的每一天创建数据点。

群组和数据点在此函数中保存得很好,但第一个循环中的|user|变量在嵌套循环中不起作用。因此,当Datapoints被保存时,它们都缺少:user_id

我很确定我只是遗漏了关于范围的内容,或者可能是.each.each_with_index行为的不同方式,但我似乎无法弄清楚问题。< / p>

Controller snippet:

# loop through all associated users
    @user_list.each do |user|
        # create join
        cohort = Cohort.new(:user_id => user, :challenge_id => @challenge.id)
        if cohort.valid?
            cohort.save
        else
            @errors += cohort.errors
        end

        # for each date in range create an empty Datapoint
        date_range.each_with_index do |day, index|
            day_count = index + 1
            datapoint = Datapoint.new(:user_id => user, :challenge_id => @challenge.id, :date => day, :day => day_count)
            if datapoint.valid?
                datapoint.save
            else
                @errors += datapoint.errors
            end
        end
    end

1 个答案:

答案 0 :(得分:0)

这个位错了,因为你要将一个复杂的对象分配给一个整数

datapoint = Datapoint.new(:user_id => user, :challenge_id => @challenge.id, :date => day, :day => day_count)

如果Datapoint实际上belongs_to user你可以做到

datapoint = Datapoint.new(:user => user, :challenge_id => @challenge.id, :date => day, :day => day_count)

但如果未定义belongs_to,则只需存储用户的ID

datapoint = Datapoint.new(:user_id => user.id, :challenge_id => @challenge.id, :date => day, :day => day_count)