未定义的方法`model_name'为3:Fixnum

时间:2015-09-17 21:22:44

标签: ruby-on-rails ruby forms ruby-on-rails-4

我定义了一个帮助方法来预先填充嵌套模型。

module MealsHelper
    def setup_meal( meal )
        add_recipes meal, 3
    end

    def add_recipes( meal,  number )
        number.times { meal.recipes.build }
    end
end

然后我把它添加到我的控制器:

class MealsController < ApplicationController
  before_action :set_meal, only: [:show, :edit, :update, :destroy]
  helper MealsHelper

然后我从我的表单中调用它:

<%= form_for(setup_meal(@meal)) do |f| %>

现在我得到了:

undefined method `model_name' for 3:Fixnum

为什么rails试图找到Fixnum的模型?

如果我跳过辅助方法,则错误消失:

<%= form_for(@meal) do |f| %>

1 个答案:

答案 0 :(得分:2)

times只会返回正在迭代的Fixnum。

尝试:

def add_recipes( meal,  number )
    number.times { meal.recipes.build }
    return meal
end